简体   繁体   中英

How can i Convert Generic List into dataTable?

I have 4 list. I want to convert these lists into Datatable with 4 columns. Each list assigned into corresponding column into 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

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]);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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