Csharp/C#教程:如何将列表转换为数据表分享


如何将列表转换为数据表

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

只需添加此函数并调用它,它就会将List转换为DataTable

public static DataTable ToDataTable(List 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; } 

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

 DataTable dt = YourList.ToDataTable(); public static DataTable ToDataTable(this List 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; } 

 static DataTable ConvertListToDataTable(List list) { // New table. DataTable table = new DataTable(); // Get max columns. int columns = 0; foreach (var array in list) { if (array.Length > columns) { columns = array.Length; } } // Add columns. for (int i = 0; i < columns; i++) { table.Columns.Add(); } // Add rows. foreach (var array in list) { table.Rows.Add(array); } return table; } protected void Button1_Click(object sender, EventArgs e) { List list = new List(); list.Add(new string[] { "Column 1", "Column 2", "Column 3" }); list.Add(new string[] { "Row 2", "Row 2" }); list.Add(new string[] { "Row 3" }); // Convert to DataTable. DataTable table = ConvertListToDataTable(list); dataGridView1.DataSource = table; } 

试试这个

上述就是C#学习教程:如何将列表转换为数据表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1026756.html

(0)
上一篇 2022年1月9日
下一篇 2022年1月9日

精彩推荐