public static DataTable CreateDataTable<T>(this IEnumerable<T> arry)
{
Type type = typeof(T);
var ret = new DataTable();
ret.TableName = type.Name;
foreach (PropertyInfo item in type.GetProperties())
{
if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("Int32"))
ret.Columns.Add(new DataColumn(item.Name, typeof(int)));
else if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("Decimal"))
ret.Columns.Add(new DataColumn(item.Name, typeof(decimal)));
else if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("Boolean"))
ret.Columns.Add(new DataColumn(item.Name, typeof(bool)));
else if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("DateTime"))
ret.Columns.Add(new DataColumn(item.Name, typeof(DateTime)));
else
ret.Columns.Add(new DataColumn(item.Name, item.PropertyType));
}
foreach (T item in arry)
{
var Row = ret.NewRow();
foreach (PropertyInfo pi in type.GetProperties())
{
if (pi.GetValue(item, null) == null)
{
Row[pi.Name] = DBNull.Value;
}
else
{
Row[pi.Name] = pi.GetValue(item, null);
}
}
ret.Rows.Add(Row);
}
return ret;
}
public static DataTable CreateDataTable<T>(this IEnumerable<T> arry, string tbName)
{
Type type = typeof(T);
var ret = new DataTable();
ret.TableName = tbName;
foreach (PropertyInfo item in type.GetProperties())
{
if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("Int32"))
ret.Columns.Add(new DataColumn(item.Name, typeof(int)));
else if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("Decimal"))
ret.Columns.Add(new DataColumn(item.Name, typeof(decimal)));
else if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("Boolean"))
ret.Columns.Add(new DataColumn(item.Name, typeof(bool)));
else if (item.PropertyType.FullName.Contains("Nullable") && item.PropertyType.FullName.Contains("DateTime"))
ret.Columns.Add(new DataColumn(item.Name, typeof(DateTime)));
else
ret.Columns.Add(new DataColumn(item.Name, item.PropertyType));
}
foreach (T item in arry)
{
var Row = ret.NewRow();
foreach (PropertyInfo pi in type.GetProperties())
{
if (pi.GetValue(item, null) == null)
{
Row[pi.Name] = DBNull.Value;
}
else
{
Row[pi.Name] = pi.GetValue(item, null);
}
}
ret.Rows.Add(Row);
}
return ret;
}
}
}