2013-09-26 80 views
5

我正在嘗試做一個列表的編號組。 例如,這LINQ查詢提供了什麼,我想在SelectMany中使用索引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如果已經持有的的SelectMany 4超負荷指數? 我試圖用接下來的方式使用這個過載,但我沒有看到解決方案。

(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) => ??????) 

回答

3

SelectManyThis overload應該工作:

(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 })) 
+0

太好了!這比我預想的要容易得多。 –