我知道在 c# 中,要从列表中获取项目可以使用 FirstOrDefault() 或其他函数。我正在寻找一个函数可以从列表中获取最多显示的项目。
例如:
{ "a" , "a" , "a" , "b" }.MostPresents() => "a"
在 c# (asp.net 4.0) 中是否有为此的默认函数?
最佳答案
Is there a default function in c# (asp.net 4.0) for this?
不,但是您可以将一些 LINQ 组合在一起并很快得到它。
var mostFrequent = sequence.GroupBy(x => x)
.Select(g => new { g.Key, Count = g.Count() })
.MaxBy(x => x.Count)
.Key;
在这里,我使用 MaxBy
.
关于c# - 如何在 C# 列表中获取最常出现的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8734110/