本文介绍了如何使用扩展方法将列表转换为数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题
将列表转换为数据表时的错误计数参数
我的列表如下
我的项目代码列表输出如下1830,950,902,540
如何转换列表字符串到数据表
我尝试过:
Problem
error mismatch count parameter when convert list to datatable
my list as below
my list output of itemcode as below "1830","950","902","540"
How to convert list of string to datatable
What I have tried:
static List<string> SimilarItems = new List<string>();
Similar = ConvertToString(dt.Rows[i]["ItemCode"]);
SimilarItems.Add(Similar);
dtcollectlistdata = Extensions.ToDataTable(SimilarItems);
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)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
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);
}
return dataTable;
}
推荐答案
List<string> mylist = new List<string>() {"1830","950","902","540"};
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("item", typeof(string)));
dt = mylist
.Select(x=> dt.LoadDataRow(new object[]{x}, false))
.CopyToDataTable();
详情请见: []
祝你好运!
For further details, please see: Creating a DataTable From a Query (LINQ to DataSet) | Microsoft Docs[^]
Good luck!
这篇关于如何使用扩展方法将列表转换为数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!