Convert generic List/Enumerable to DataTable?

后端 未结 27 2189
臣服心动
臣服心动 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-22 00:06

    try this

    public static DataTable ListToDataTable(IList lst)
    {
    
        currentDT = CreateTable();
    
        Type entType = typeof(T);
    
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
        foreach (T item in lst)
        {
            DataRow row = currentDT.NewRow();
            foreach (PropertyDescriptor prop in properties)
            {
    
                if (prop.PropertyType == typeof(Nullable) || prop.PropertyType == typeof(Nullable) || prop.PropertyType == typeof(Nullable))
                {
                    if (prop.GetValue(item) == null)
                        row[prop.Name] = 0;
                    else
                        row[prop.Name] = prop.GetValue(item);
                }
                else
                    row[prop.Name] = prop.GetValue(item);                    
    
            }
            currentDT.Rows.Add(row);
        }
    
        return currentDT;
    }
    
    public static DataTable CreateTable()
    {
        Type entType = typeof(T);
        DataTable tbl = new DataTable(DTName);
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
        foreach (PropertyDescriptor prop in properties)
        {
            if (prop.PropertyType == typeof(Nullable))
                 tbl.Columns.Add(prop.Name, typeof(decimal));
            else if (prop.PropertyType == typeof(Nullable))
                tbl.Columns.Add(prop.Name, typeof(int));
            else if (prop.PropertyType == typeof(Nullable))
                tbl.Columns.Add(prop.Name, typeof(Int64));
            else
                 tbl.Columns.Add(prop.Name, prop.PropertyType);
        }
        return tbl;
    }
    

提交回复
热议问题