0

我需要在分组后用它的位置索引项目列表

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 获取列表的项目索引?

4

2 回答 2

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()
                               });
于 2013-09-04T12:00:47.723 回答
0
var idx = 0;
var result = from i in items
             group i by i.name into g
             select new { product = g.Key, 
                          index = idx++
                        };
于 2013-09-04T12:01:07.603 回答