Question

I am trying to create a datatable from the following lists

**List1**
1
2
3
4
5

**List2**
foo1
foo2
foo3
foo4
foo5

The final table should look like this (name of the col doens't matter)

SomeName1   SomeName2
1           foo1
2           foo2
3           foo3
4           foo4
5           foo5

I am trying to avoid referring respective indexes of both the lists and adding them as rows

is there a better way of doing this?

EDIT: I can have any number of lists not just 2

Was it helpful?

Solution

This will deal with any number of IEnumerable.

private static void Main(string[] args)
{
    var list1 = new List<int>(new[] { 1, 2, 3, 4, 5 });
    var list2 = new List<string>(new[] { "foo1", "foo2", "foo3", "foo4", "foo5" });
    var list3 = new List<bool>(new[] {true, false, true, true, false});

    var dt = MakeDataTable(list1, list2, list3);

    Console.ReadLine();

}

private static DataTable MakeDataTable(params IEnumerable[] lists)
{
    var dt = new DataTable();
    for (var i = 0; i < lists.Length; i++)
    {
        dt.Columns.Add("column" + i);
    }
    foreach (var data in CombineList(lists))
    {
        dt.Rows.Add(data);
    }

    return dt;
}

private static IEnumerable<object[]> CombineList(params IEnumerable[] lists)
{
    var enumerators = lists.Select(l=>l.GetEnumerator()).ToArray();
    while (enumerators.All(e => e.MoveNext()))
    {
       yield return enumerators.Select(e => e.Current).ToArray();
    }
}

OTHER TIPS

You can try this:

public DataTable GetTable(List list1, List list2)
{
 DataTable table = new DataTable();
 table.Columns.Add("SomeName1", typeof(int));
 table.Columns.Add("SomeName2", typeof(string));
 var collection = list1.Join(list2, x => x, y => y, (x, y) => new { X = x, Y = y });
 foreach ( var row in collection) 
   {
    table.Rows.Add(row.x, row.y);
   }
 return table;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top