Rafael Seidalinov
Rafael Seidalinov

Reputation: 181

Using index in SelectMany 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) => ??????) 

Upvotes: 9

Views: 6281

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149010

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 }))

Upvotes: 8

Related Questions