我有一个名为 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当前元素
答案 0 :(得分:5)
这是使用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
}
}
}