在Select语句中获取列表的项索引

时间:2013-09-04 11:59:02

标签: c# linq lambda

我需要在分组后将项目列表的位置编入索引

var result = from i in items
             group i by i.name into g
             select new { groupname = g.Key, 
                          index = //need to get the index of the item
                        };

如何使用linq / lambda获取列表的项索引?

2 个答案:

答案 0 :(得分:7)

我不是100%肯定你想要实现的目标,但我绝对建议使用方法而不是基于语法的查询。

var results = items.GroupBy(x => x.name)
                   .Select((g, i) => new { product = g.Key, index = i });

或者,如果您希望从每个组中的所有项目获取源代码索引:

var results = items.Select((x, i) => new { x, i })
                   .GroupBy(x => x.x.name)
                   .Select(g => new {
                                   product = g.Key,
                                   indexes = g.Select(x => x.i).ToList()
                               });

答案 1 :(得分:0)

var idx = 0;
var result = from i in items
             group i by i.name into g
             select new { product = g.Key, 
                          index = idx++
                        };