LINQ Inserts

I have an unsorted list of ints:

1 3 1 2 4 3 2 1 

I need to sort it, and in front of each group of equal numbers, insert 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 only one LINQ statement? I'm stuck in

 from num in numbers orderby num select num 

followed by a foreach loop that manually creates the final output based on these results. I would like to completely eliminate the second cycle, if possible.

+4
source share
3 answers

Try:

 list.GroupBy(n => n) .OrderBy(g => g.Key) .SelectMany(g => new[] { 0 }.Concat(g)) 

For each group of numbers, add 0, and then flatten the list with SelectMany .

And in the query syntax:

 from num in list group num by num into groupOfNums orderby groupOfNums.Key from n in new[] { 0 }.Concat(groupOfNums) select n 
+8
source
 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(); 
+6
source

Try it on LinqPad.

 var list = new int[]{1, 3, 1, 2, 4, 3, 2, 1}; var q = from x in list orderby x group x by x into xs from y in (new int[]{0}).Concat(xs) select y; q.Dump(); 

This will give you the desired result.

+1
source

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


All Articles