如何将列表转换为数据表

42

我有一个具有某些属性的数据列表。我想将该列表数据转换为数据表格。如何将列表转换为数据表格。


你能告诉我们列表中的对象类型吗? - Kirill Bestemyanov
3个回答

143

添加这个函数并调用它,它将把List转换为DataTable。

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);
    
        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

2
如何调用这个函数。谢谢回复。 - user2660267
3
假设您有一个用户列表:List<User> rm = new List<User>(); User类中有FirstName、LastName、Address等属性。要将此列表转换为DataTable,只需使用以下代码: DataTable UserDt = rm.ToDataTable(); - Harshil Raval
3
好的,我知道了,system.reflection; - Badhon Jain
1
点击类名下面有红线的地方(如语法错误),然后按ALT+SHIFT+F10。它会显示命名空间。选择顶部的System.Reflection。 - Shezi
1
上述答案给出了“参数数量不匹配”的额外信息。 - Jogi
显示剩余8条评论

19

您可以使用这个扩展方法,并像这样调用它。

DataTable dt =   YourList.ToDataTable();

public static DataTable ToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

正是我在寻找的! - Mark Kram
这会为我提供一个string类型的List的数值。 - Jogi

-1
private DataTable CreateDataTable(IList<T> 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;
}

3
在dotnet中,除非您访问此页面并找到此方法的代码“http://social.msdn.microsoft.com/Forums/vstudio/en-US/6ffcb247-77fb-40b4-bcba-08ba377ab9db/converting-a-list-”,否则无法识别“ConvertListToDataTable(...);”。 - Bellash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接