这是我想出的解决方案的示例
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int[] arr = new int[] { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
var countlist = arr.Aggregate(new Dictionary<int,int>(), (D,i) => {
D[i] = D.ContainsKey(i) ? (D[i] + 1) : 1;
return D;
})
.AsQueryable()
.OrderByDescending(x => x.Value)
.Select(x => x.Key)
.ToList();
// print the element which appears with the second
// highest frequency in arr
Console.WriteLine(countlist[2]); // should print 3
}
}
至少,我想弄清楚如何去做
至少减少一个查询子句。虽然我没有看到任何冗余,但这是 LINQ 查询的类型,我担心创建的所有中间结构的所有开销。
弄清楚如何在最后不返回整个列表。我只想要枚举序列中的第二个元素;我不需要为了从中获取单个元素而返回整个列表。
最佳答案
int[] arr = new int[] { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
var lookup = arr.ToLookup(t => t);
var result = lookup.OrderByDescending(t => t.Count());
Console.WriteLine(result.ElementAt(1).Key);
关于c# - 如何使查找数组中第 N 个最频繁元素的过程更加高效和紧凑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006865/