LINQ gets global index

I have a structure:

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

How to project it in the 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 the resulting element should represent the global index of the base element, and the second should represent the index of the group for which this element belongs.

Example: the 2nd element of the 3rd group will be projected onto {8.3}:

8 - global index of the base element

3 - the index of the base element of the group belongs.

+6
source share
1 answer

You can do this using versions of Select and SelectMany that include an 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}

+4
source

Source: https://habr.com/ru/post/1011768/


All Articles