插入LINQ

Eri*_*c B 4 c# linq

我有一个未排序的整数列表:

1 3 1 2 4 3 2 1
Run Code Online (Sandbox Code Playgroud)

我需要对它进行排序,在每组相等数字之前插入一个0:

0 1 1 1 0 2 2 0 3 3 0 4
Run Code Online (Sandbox Code Playgroud)

有一种方法只用一个LINQ语句从第一个列表到第二个列表?我被困住了

from num in numbers
orderby num
select num
Run Code Online (Sandbox Code Playgroud)

然后是foreach循环,根据这些结果手动构建最终输出.如果可能的话,我想完全消除第二个循环.

Ben*_*ich 8

尝试:

list.GroupBy(n => n)
      .OrderBy(g => g.Key)
      .SelectMany(g => new[] { 0 }.Concat(g))
Run Code Online (Sandbox Code Playgroud)

对于每组数字,前置0,然后用列表展平列表SelectMany.

在查询语法中:

from num in list
group num by num into groupOfNums
orderby groupOfNums.Key
from n in new[] { 0 }.Concat(groupOfNums)
select n
Run Code Online (Sandbox Code Playgroud)


I4V*_*I4V 6

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();
Run Code Online (Sandbox Code Playgroud)