c# - 将 IEnumerable 转换为 DataTable

标签 c# datatable ienumerable

是否有将 IEnumerable 转换为 DataTable 的好方法?

我可以使用反射来获取属性和值,但这似乎有点低效,是否有内置的东西?

(我知道这样的例子:ObtainDataTableFromIEnumerable)

编辑:
question通知我处理空值时出现问题。
我在下面编写的代码正确处理了空值。

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

最佳答案

看看这个:Convert List/IEnumerable to 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;
}

关于c# - 将 IEnumerable 转换为 DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1253725/

相关文章:

c# - MVC 5 中用于多选的 ViewModel 属性

c# - 如何使用字段 ID 从 SQL Server 数据库中获取字段名

javascript - 渲染事件后是否有 YUI 数据表?

javascript - jQuery DataTable - 使用自定义 JSON 结构显示数据

wcf - 在 WCF 中使用 IEnumerable 类型作为返回类型的问题

c# - 如何获取 IEnumerable 中元素的索引?

c# - 编译为空的虚拟 IEnumerable<T>

c# - 将 Include() 重写为 linq 连接

c# - 在基类中使用动态关键字和调用泛型方法导致 StackOverflowException

c# - 如何使用 C# 过滤具有多列值的数据表