遍历 IEnumerable<object>

Loop through IEnumerable<object>

我正在使用 enumerable 和 group by LINQ 对来自具有 5 列的 DataTable 的数据进行分组。现在我需要访问结果中的每一列数据。

编辑:

    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
        }

属性的名称是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 };
}

修改后

您不应传递给其他 functions/return 匿名对象(技术上可以,但不应该)。参见 and 。如果你真的想要,你可以使用 dynamic

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

对于这个问题我有另一个解决方案,我试过了并且对我有用。我使用反射如下;

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();