Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using index in SelectMany LINQ

Tags:

c#

linq

I am trying to do numbered groups of a list. For example this LINQ query gives what I want

(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 

But I decided to optimize this query: Why we need use external to SelectMany index if it has own index in 4th overload of SelectMany? And I tried to use this overload in next way, but I do not see the solution.

(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) => ??????) 
like image 269
Rafael Seidalinov Avatar asked Sep 26 '13 12:09

Rafael Seidalinov


1 Answers

This overload of SelectMany should work:

(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 }))
like image 111
p.s.w.g Avatar answered Nov 06 '22 16:11

p.s.w.g