8

我正在尝试对列表进行编号组。例如这个 LINQ 查询给出了我想要的

(from word in "The quick brown fox jumps over the lazy dog" .Split()
group word by word.Length into w
select w)
.Select((value, index) => new { i = index + 1, value })
.SelectMany(
sm => sm.value,
(sm, s) => new { sm.i, s})

1 The 
1 fox 
1 the 
1 dog 
2 quick 
2 brown 
2 jumps 
3 over 
3 lazy 

但我决定优化这个查询:如果在 SelectMany 的第 4 次重载中有自己的索引,为什么我们需要使用 SelectMany 索引的外部?我尝试在下一个方式中使用这个重载,但我没有看到解决方案。

(from word in "The quick brown fox jumps over the lazy dog".Split()
           group word by word.Length into w
           select w)
                .SelectMany(
                (source, index) => ??????,
                (msource, coll) => ??????) 
4

1 回答 1

7

这种重载SelectMany应该起作用:

(from word in "The quick brown fox jumps over the lazy dog".Split()
 group word by word.Length into g
 select g)
.SelectMany((g, i) => g.Select(word => new { index = i + 1, word }))
于 2013-09-26T13:10:40.393 回答