2013-09-26 11 views
5

Sto tentando di eseguire gruppi numerati di un elenco. Per esempio questa query LINQ dà quello che voglioUso dell'indice in 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 

Ma ho deciso di ottimizzare questa domanda: Perché abbiamo bisogno uso esterno per indicizzare SelectMany se è proprio indice in 4 ° sovraccarico SelectMany? E ho provato a utilizzare questo overload in modo successivo, ma non vedo la soluzione.

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

risposta

3

This overload di SelectMany dovrebbe funzionare:

(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

Grande! È molto più facile di quanto mi aspettassi. –

Problemi correlati