简体   繁体   English

如何将通用列表转换为dataTable?

[英]How can i Convert Generic List into dataTable?

I have 4 list. 我有4个清单。 I want to convert these lists into Datatable with 4 columns. 我想将这些列表转换为具有4列的Datatable。 Each list assigned into corresponding column into DataTable. 每个列表分配到DataTable的对应列中。

List<string> list1;
List<string> list2;
List<string> list3;
// and 
List<string> list4;

this i want to convert datatable as 这我想将数据表转换为

columns: List1 List2 List3 List4 列:List1 List2 List3 List4

Can anyone tell me Easy Solution for this? 谁能告诉我简易解决方案吗?

haven't tried it outside of just making sure it builds, runs, and seems to populate the datatable fine. 除了确保它可以生成,运行并似乎可以很好地填充数据表之外,还没有尝试过它。

        var dataTable = new DataTable();
        dataTable.Columns.Add("Col1", list1.GetType().GetGenericArguments().First());
        dataTable.Columns.Add("Col2", list2.GetType().GetGenericArguments().First());
        dataTable.Columns.Add("Col3", list3.GetType().GetGenericArguments().First());
        dataTable.Columns.Add("Col4", list4.GetType().GetGenericArguments().First());

        // assumes they all match on count
        for (int i = 0; i < list1.Count; i++)
        {
            dataTable.Rows.Add(list1[i], 
                               list2[i],
                               list3[i],
                               list4[i]);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM