我有以下数组:
var arr = new[] { 1, 1, 2, 2, 4 };
现在我想按频率对这个数组进行排序:
具有频率的数字子集是1 [4]
频率为2的数字子集为[1,2]
然后我们按自然顺序对具有相同频率的每个元素子集进行排序,得到[1,3,4,2,2]
为此,我写了以下linq查询,但我被困了
var line in arr.GroupBy(n => n)
// Order by the frequency of each group of numbers
.OrderBy(g => g.Count())
// Then by the natural order of each number
.ThenBy(g => g.Key)
.??
答案 0 :(得分:3)
您可以按重复次数对数字进行分组,对组进行排序并对每个组的元素进行排序:
var result = arr.GroupBy(n => arr.Count(i => i == n))
.OrderBy(g => g.Key)
.SelectMany(g => g.OrderBy(x => x));
或
var result = arr.GroupBy(n => n)
.OrderBy(g => g.Count())
.ThenBy(g => g.Key)
.SelectMany(g => g);
答案 1 :(得分:1)
你很亲密。您可以按照Ya Weng提到的group.Count
进行排序,然后使用SelectMany
将结果投影到您需要的数组中。
您也可以通过省略Select
步骤来简化操作(因为GroupBy
已将其投影到您的分组中):
var arr = new[] { 3, 1, 2, 2, 4 };
var result = arr.GroupBy(n => n)
// Order by the frequency of each group of numbers
.OrderBy(g => g.Count())
// Then by the natural order of each number
.ThenBy(g => g.Key)
// Project the groups back to a flat array
.SelectMany(g => g);
Console.WriteLine(string.Join(",", result));
// => 1,3,4,2,2
这是尝试的小提琴:https://dotnetfiddle.net/y3vOi7
答案 2 :(得分:1)
这很简单
var res = arr.OrderBy(n=>
arr.Count(x => x == n) ) .ThenBy (n => n);
按频率排序(然后按自然顺序排序),仅此而已
答案 3 :(得分:0)
在LINQ查询语法中。
var ret = string.Join(",", from n in new[] { 3, 1, 2, 2, 4}
group n by n into x
orderby x.Count(), x.Key
from i in x
select i);
// ret = "1,3,4,2,2"