C# – Loop through IEnumerable

cienumerablelinqobject

I'm using enumerable and group by LINQ to group data from a DataTable with 5 columns. Now I need to access each column data in result.

EDIT:

    private IEnumerable<object> getItemsForDisplay()
    {
           var result = toDisplay.AsEnumerable()
             .GroupBy(x => new
             {
                 Col1 = x.Field<string>("rItem"),
                 Col2 = x.Field<string>("rMaterial"),
                 Col3 = x.Field<string>("rSpecs")
             })
            .Select(g => new
            {
                Col1 = g.Key.Col1,
                Col2 = g.Key.Col2,
                Col3 = g.Key.Col3,
                Col4 = String.Join(", ", g.Select(row => row.Field<string>("rQuantity"))),
                Col5 = String.Join(", ", g.Select(row => row.Field<string>("rOptional"))),
            }).ToList();
         return result;
  }

         //In another function
         foreach (var item in result)
        {
            //item.tostring shows this: {"aaa","bbb","ccc","ddd","eee")
            //turn it to array string or list to access "aaa".. etc etc
        }

Best Answer

The name of the properties are Col1... Col5

foreach (var item in result)
{
    Console.WriteLine(item.Col1);
    Console.WriteLine(item.Col2);
    Console.WriteLine(item.Col3);
    Console.WriteLine(item.Col4);
    Console.WriteLine(item.Col5);

    // If you want an array:
    var arr = new string[] { item.Col1, item.Col2, item.Col3, item.Col4, item.Col5 };
}

after revision

You shouldn't pass to other functions/return anonymous objects (technically you can, but you shouldn't). See https://stackoverflow.com/a/6625008/613130 and https://stackoverflow.com/a/18189923/613130 . You can use dynamic if you really want.

foreach (dynamic item in result)
{
    Console.WriteLine(item.Col1);
    Console.WriteLine(item.Col2);
    Console.WriteLine(item.Col3);
    Console.WriteLine(item.Col4);
    Console.WriteLine(item.Col5);

    // If you want an array:
    var arr = new string[] { item.Col1, item.Col2, item.Col3, item.Col4, item.Col5 };
}