小编典典

将IEnumerable转换为DataTable

c#

有没有一种很好的方法将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); 
    }

    // 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; 
}

阅读 691

收藏
2020-05-19

共1个答案

小编典典

看一看: 将List / IEnumerable转换为DataTable /
DataView

在我的代码中,我将其更改为扩展方法:

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;
}
2020-05-19