Reputation: 1592
I have a data set something like this:
2,Black
2,Blue
2,Red
1,Small
1,Medium
I need to convert this into the following:
2_0
2_1
2_2
1_0
1_1
The LINQ query I have at the moment uses an index for the second number, however it doesn't reset to 0 when changing from 2_ to 1_. I've tried using a GroupBy, but I can't get the results I need - can anyone help?
Upvotes: 0
Views: 104
Reputation: 2521
You can group by the number and use the version of Select()
that provides the index:
var result = data.GroupBy(x => x.Number,
(key, g) => g.Select((_, i) => string.Format("{0}_{1}", key, i)))
.SelectMany(x => x);
Note that this might behave differently than you'd expect if the same numbers aren't contiguous: e.g, 2, 2, 2, 1, 1, 2, 2
.
Upvotes: 1
Reputation: 144136
IEnumerable<string> output = input
.GroupBy(i => i.Num)
.SelectMany(grp => grp.Select((item, idx) => string.Format("{0}_{1}", grp.Key, idx)));
Upvotes: 3