首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用for循环遍历Linq组结果集

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

Stack Overflow用户
提问于 2017-01-10 03:51:11
回答 1查看 5.9K关注 0票数 4

我有一个名为myGroup的Linq组结果集。myGroup是一种

IGrouping < String,myObject >

我正试图通过for循环来迭代这一过程。

目前,我可以这样做:

代码语言:javascript
复制
foreach (var item in group)
{
    Console.WriteLine(item.Id);
}

如何实现使用for循环的相同功能?

我试着做如下的事情:

代码语言:javascript
复制
   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当前元素

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-10 04:03:29

下面是一个使用ElementAt()的工作示例:

代码语言:javascript
复制
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
        }
    }
}
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41560834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档