Loop through IEnumerable<object>

21.5k Views Asked by At

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
        }
2

There are 2 best solutions below

1
On 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 };
}
1
On

I have another solution for this issue, i tried and it worked for me. I used reflection as below;

IEnumerable<object> query = result.Select(x => new {
    Col1 = x.GetType().GetProperty("Col1").GetValue(x, null).ToString() ?? "",
    Col2 = x.GetType().GetProperty("Col2").GetValue(x, null).ToString() ?? "",
    Col3 = x.GetType().GetProperty("Col3").GetValue(x, null).ToString() ?? "",
    Col4 = x.GetType().GetProperty("Col4").GetValue(x, null).ToString() ?? "",
    Col5 = x.GetType().GetProperty("Col5").GetValue(x, null).ToString() ?? "",
}).ToList();