Loop through IEnumerable<object>

18,273

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 };
}
Share:
18,273
Miroxen
Author by

Miroxen

Updated on June 05, 2022

Comments

  • Miroxen
    Miroxen almost 2 years

    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
            }
    
  • xanatos
    xanatos almost 9 years
    @Miroxen Updated response.
  • Miroxen
    Miroxen almost 9 years
    Thanks. I created a list of list string, populated a temp list for each row and then added it to the list of list string.
  • Abdurrahman I.
    Abdurrahman I. almost 7 years
    @huseyint That's definitely not quite well solution and i wrote this 1,5 years ago. I'm not sure but the reflection calls could've be outside to loop