LINQ或Lamba在它们的重复频率集内按升序对整数数组进行排序

时间:2017-01-11 14:13:55

标签: c# linq lambda

我的输入如下

int[] arr = new int[] { 3, 1, 2, 2, 4, 6, 6, 9, 9, 9, 7, 7, 7};

如图所示,

3,1,4 are repeated only 1 time
2, 6 are repeated 2 times each
9, 7 are repeated 3 times each.

如何编写逻辑来排序数组,使得它们在出现频率的集合中按升序排列

上面数组的预期输出是     1, 3, 4, 2, 2, 6, 6, 7, 7, 7, 9, 9, 9

我的尝试:

var res = (arr.OrderBy(i => i).Reverse()
            .GroupBy(x => x)
            .Where(g => g.Count() >= 1)
            .ToDictionary(x => x.Key, y => y.Count())
            .Select(x => x) // stuck here
            ).ToList();

1 个答案:

答案 0 :(得分:10)

尝试这样的事情:

var result = arr.GroupBy(x => x)
                .OrderBy(g => g.Count())
                .ThenBy(g => g.Key)
                .SelectMany(g => g);

这将对元素进行分组,首先按元素数量(升序)排序,然后按元素值排序,最后压平为可枚举元素。