Convert generic List/Enumerable to DataTable?

后端 未结 27 2570
臣服心动
臣服心动 2020-11-21 23:20

I have few methods that returns different Generic Lists.

Exists in .net any class static method or whatever to convert any list into a datatable? The only thing tha

27条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 23:58

    I had to modify Marc Gravell's sample code to handle nullable types and null values. I have included a working version below. Thanks Marc.

    public static DataTable ToDataTable(this IList data)
    {
        PropertyDescriptorCollection properties = 
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                 row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
    

提交回复
热议问题