使用for循环遍历Linq分组结果集

5
我有一个名为 myGroup 的Linq组结果集。myGroup是一种 IGrouping<String,myObject>类型。我正在尝试通过 for 循环迭代它。

目前,我可以像这样做:

foreach (var item in group)
{
    Console.WriteLine(item.Id);
}

如何使用for循环实现同样的功能?
我尝试像下面这样做:
   for (int i = 0; i < myGroup.Count(); i++)
         {
          // Now How can I access the current myGroup Item?
          //I DO NOT have ElementAt() property in myGroup.
          myGroup.ElementAt(i).Id // THIS IS NOT POSSIBLE
         }

但是我不知道如何在for循环中访问myGroup当前元素。

你为什么特别想要转换到使用 for 循环呢? - Prajwal
为什么无法使用ElementAt()?有任何错误吗? - IDeveloper
@Benjamin,你能否请发一下你的所有“using”语句吗? - IDeveloper
@Benjamin,你添加了 using System.Linq 吗? - Balaji Marimuthu
抱歉,是我的错。这是由于使用语句引起的。谢谢 @IDeveloper。 - Benjamin
显示剩余4条评论
1个回答

11

这里是使用ElementAt()的工作示例:

public class Thing
{
    public string Category { get; set; }
    public string Item { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var foos = new List<Thing>
        {
            new Thing { Category = "Fruit", Item = "Apple" },
            new Thing { Category = "Fruit", Item = "Orange" },
            new Thing { Category = "Fruit", Item = "Banana" },
            new Thing { Category = "Vegetable", Item = "Potato" },
            new Thing { Category = "Vegetable", Item = "Carrot" }
        };

        var group = foos.GroupBy(f => f.Category).First();

        for (int i = 0; i < group.Count(); i++)
        {
            Console.WriteLine(group.ElementAt(i).Item); //works great
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接