将 IEnumerable 转换为 DataTable [英] Convert IEnumerable to DataTable
本文介绍了将 IEnumerable 转换为 DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有将 IEnumerable 转换为 DataTable 的好方法?
Is there a nice way to convert an IEnumerable to a DataTable?
我可以使用反射来获取属性和值,但这似乎有点低效,是否有内置的东西?
I could use reflection to get the properties and the values, but that seems a bit inefficient, is there something build-in?
(我知道这样的例子:ObtainDataTableFromIEnumerable)
编辑:
这个问题通知我处理空值时出现问题.
我在下面编写的代码正确处理了空值.
EDIT:
This question notified me of a problem handling null values.
The code I wrote below handles the null values properly.
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);
}
// Add the property values per T as rows to the datatable
foreach (var item in items) {
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
values[i] = props[i].GetValue(item, null);
table.Rows.Add(values);
}
return table;
}
推荐答案
看这个:将 List/IEnumerable 转换为 DataTable/DataView
在我的代码中,我将其更改为扩展方法:
In my code I changed it into a extension method:
public static DataTable ToDataTable<T>(this List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(var prop in props)
{
tb.Columns.Add(prop.Name, prop.PropertyType);
}
foreach (var item in items)
{
var values = new object[props.Length];
for (var i=0; i<props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
这篇关于将 IEnumerable 转换为 DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文