有没有一种很好的方法将IEnumerable转换为DataTable?
我可以使用反射来获取属性和值,但这似乎有点低效,是否有内置的东西?
(我知道这些例子:ObtainDataTableFromIEnumerable)
编辑:
这个问题通知我处理空值的问题.
我在下面写的代码正确处理空值.
public static DataTable ToDataTable<T>(this IEnumerable<T> items) {
// Create the result table, and gather all properties of a T
DataTable table = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Add the properties as columns to the datatable
foreach (var prop in props) {
Type propType = prop.PropertyType;
// Is it a nullable type? Get the underlying type
if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
propType = new NullableConverter(propType).UnderlyingType;
table.Columns.Add(prop.Name, propType);
}
// …Run Code Online (Sandbox Code Playgroud) 我有一个DataTable有两列.ShipmentDate(DateTime)和Count(Int).在我反序列化字符串之后,我注意到如果第一个itemarray值为null,ShipmentDate的类型就变成了字符串.
请查看以下示例.除第一个数组项外,json字符串都有相同的数据.
string jsonTable1 = "[{\"ShipmentDate\":null,\"Count\":3},{\"ShipmentDate\":\"2015-05-13T00:00:00\",\"Count\":13},{\"ShipmentDate\":\"2015-05-19T00:00:00\",\"Count\":1},{\"ShipmentDate\":\"2015-05-26T00:00:00\",\"Count\":1},{\"ShipmentDate\":\"2015-05-28T00:00:00\",\"Count\":2}]";
string jsonTable2 = "[{\"ShipmentDate\":\"2015-05-13T00:00:00\",\"Count\":13},{\"ShipmentDate\":null,\"Count\":3},{\"ShipmentDate\":\"2015-05-19T00:00:00\",\"Count\":1},{\"ShipmentDate\":\"2015-05-26T00:00:00\",\"Count\":1},{\"ShipmentDate\":\"2015-05-28T00:00:00\",\"Count\":2}]";
DataTable tbl1 = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(jsonTable1);
DataTable tbl2 = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(jsonTable2);
Console.WriteLine(tbl1.Columns["ShipmentDate"].DataType);
Console.WriteLine(tbl2.Columns["ShipmentDate"].DataType);
Run Code Online (Sandbox Code Playgroud)
在我的场景中,第一个项目数组的ShipmentDate可以为null,并通过将其转换为字符串类型来创建问题.
我有一种情况,数据表的模式是动态的.我无法创建强类型类.