0

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?

sankar
  • 75
  • 1
  • 7

1 Answers1

1

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]);
        }
James Manning
  • 13,429
  • 2
  • 40
  • 64
  • Actually, he already said the lists are all strings, so you can skip the reflection. The only other issue I see offhand is that the lists might be of different lengths, but that's something he's going to have to worry about. With his awful design. –  Aug 12 '10 at 13:38
  • Yes i tried this way this ok...but i want to Do new way to add the list into datatable... – sankar Aug 13 '10 at 06:22