I have an unsorted list of ints:
1 3 1 2 4 3 2 1
I need to sort it, and before each group of equal numbers, insert a 0:
0 1 1 1 0 2 2 0 3 3 0 4
Is there a way to get from the first list to the second list with just one LINQ statement? I'm stuck at
from num in numbers
orderby num
select num
followed by a foreach loop that manually constructs the final output based on these results. I'd like to eliminate the second loop entirely, if possible.
Try:
list.GroupBy(n => n)
.OrderBy(g => g.Key)
.SelectMany(g => new[] { 0 }.Concat(g))
For each group of numbers, prepend 0, and then flatten the list with SelectMany
.
And in query syntax:
from num in list
group num by num into groupOfNums
orderby groupOfNums.Key
from n in new[] { 0 }.Concat(groupOfNums)
select n
int[] nums = { 1, 3, 1, 2, 4, 3 ,2 ,1};
var newlist = nums.GroupBy(x => x)
.OrderBy(x=>x.Key)
.SelectMany(g => new[] { 0 }.Concat(g)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With