Convert generic List/Enumerable to DataTable?

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

      private DataTable CreateDataTable(IList item)
            {
                Type type = typeof(T);
                var properties = type.GetProperties();
    
                DataTable dataTable = new DataTable();
                foreach (PropertyInfo info in properties)
                {
                    dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
                }
    
                foreach (T entity in item)
                {
                    object[] values = new object[properties.Length];
                    for (int i = 0; i < properties.Length; i++)
                    {
                        values[i] = properties[i].GetValue(entity);
                    }
    
                    dataTable.Rows.Add(values);
                }
                return dataTable;
            }
    

提交回复
热议问题