我有一个名为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当前元素
发布于 2017-01-10 04:03:29
下面是一个使用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
}
}
}https://stackoverflow.com/questions/41560834
复制相似问题