正在做的项目里面有需要把DAL 产生的Poco Collection转为DataTable然后交给别的模块处理报表
想了一下 写个支持Generic的方法吧, 不过不知道如何判断 T是否是DynamicObject的类型
于是取了第一个item,用它来判断一下,这样写肯定不是最好的,把code贴上抛砖引玉。
public static DataTable ToDataTable<T>(IEnumerable<T> input, string tableName)
{
var dt = new DataTable();
dt.TableName = tableName;
var first = Enumerable.First(input);
if (first is System.Dynamic.DynamicObject)
{
IDictionary<string, object> properties = (IDictionary<string, object>)first;
foreach (var p in properties)
{
var type = p.Value.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = type.GetGenericArguments()[0];
dt.Columns.Add(p.Key, type);
}
foreach (T r in input)
{
var values = new object[properties.Count];
int i = 0;
foreach (var p in properties)
{
values[i] = (r as IDictionary<string, object>)[p.Key];
i++;
}
dt.LoadDataRow(values, true);
}
}
else
{
var properties = typeof(T).GetProperties();
foreach (var p in properties)
{
var type = p.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = type.GetGenericArguments()[0];
dt.Columns.Add(p.Name, type);
}
foreach (T r in input)
{
var values = new object[properties.Length];
int i = 0;
foreach (var p in properties)
{
values[i] = p.GetValue(r, null);
i++;
}
dt.LoadDataRow(values, true);
}
}
return dt;
}