Reputation: 297
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.
Upvotes: 6
Views: 105
Reputation: 32296
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}
Upvotes: 4