Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ get global index

Tags:

c#

linq

I have structure:

List<List<x>> structure = new { {x,x}, {x,x,x,x}, {x,x,x}}

How can project it to following sequence using linq?

{1,1},{2,1},{3,2},{4,2},{5,2},{6,2},{7,3},{8,3},{9,3}

So the first property of resulting element must represent global index of base element and the second one must represent index of group for which that element belongs to.

Example: 2nd element of 3rd group will be projected to {8,3}:

8 - global index of base element

3 - index of group base element belongs to.

like image 278
Sic Avatar asked Oct 27 '16 12:10

Sic


1 Answers

You can do that by using the versions of Select and SelectMany that include the index.

IList<IList<int>> structure = new[] 
{ 
    new[] { 1, 1 }, 
    new[] { 1, 1, 1, 1 }, 
    new[] { 1, 1, 1 } 
};

var result = structure.SelectMany((l, i) => l.Select(v => i))
    .Select((i, j) => new[] {j + 1, i + 1});

Console.WriteLine(string.Join(",", result.Select(l => "{" + string.Join(",", l) + "}")));

Outputs

{1,1},{2,1},{3,2},{4,2},{5,2},{6,2},{7,3},{8,3},{9,3}

like image 190
juharr Avatar answered Oct 25 '22 04:10

juharr