public
static
class IQueryableExtensions
{
public static DataTable ToDataTable( this IQueryable list)
{
DataTable dt = new DataTable();
bool schemaIsBuild = false;
PropertyInfo[] props = null;
foreach ( object item in list)
{
if (!schemaIsBuild)
{
props = item.GetType().GetProperties();
foreach ( var pi in props)
{
Type piType = pi.PropertyType;
if (piType.IsGenericType && piType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
piType = piType.GetGenericArguments()[ 0];
}
dt.Columns.Add( new DataColumn(pi.Name, piType));
}
schemaIsBuild = true;
}
var row = dt.NewRow();
foreach ( var pi in props)
{
row[pi.Name] = pi.GetValue(item, null) == null ? DBNull.Value : pi.GetValue(item, null);
}
dt.Rows.Add(row);
}
dt.AcceptChanges();
return dt;
}
}
{
public static DataTable ToDataTable( this IQueryable list)
{
DataTable dt = new DataTable();
bool schemaIsBuild = false;
PropertyInfo[] props = null;
foreach ( object item in list)
{
if (!schemaIsBuild)
{
props = item.GetType().GetProperties();
foreach ( var pi in props)
{
Type piType = pi.PropertyType;
if (piType.IsGenericType && piType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
piType = piType.GetGenericArguments()[ 0];
}
dt.Columns.Add( new DataColumn(pi.Name, piType));
}
schemaIsBuild = true;
}
var row = dt.NewRow();
foreach ( var pi in props)
{
row[pi.Name] = pi.GetValue(item, null) == null ? DBNull.Value : pi.GetValue(item, null);
}
dt.Rows.Add(row);
}
dt.AcceptChanges();
return dt;
}
}