Convert generic List/Enumerable to DataTable?

后端 未结 27 2581
臣服心动
臣服心动 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:56

    I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable which returned an IEnumerable and the properties couldn't be enumerated. This did the trick:

    // remove "this" if not on C# 3.0 / .NET 3.5
    public static DataTable ConvertToDataTable(this IEnumerable data)
    {
        List list = data.Cast().ToList();
    
        PropertyDescriptorCollection props = null;
        DataTable table = new DataTable();
        if (list != null && list.Count > 0)
        {
            props = TypeDescriptor.GetProperties(list[0]);
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            }
        }
        if (props != null)
        {
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item) ?? DBNull.Value;
                }
                table.Rows.Add(values);
            }
        }
        return table;
    }
    

提交回复
热议问题