Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insertions with LINQ

Tags:

c#

linq

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.

like image 316
Eric B Avatar asked Dec 06 '22 07:12

Eric B


2 Answers

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
like image 189
Ben Reich Avatar answered Dec 30 '22 12:12

Ben Reich


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();
like image 27
I4V Avatar answered Dec 30 '22 11:12

I4V