[英]How to get most presented items in a List of c#?
I know in c#, to get a item from a list can use FirstOrDefault() or other functions. 我知道在c#中,要从列表中获取项目,可以使用FirstOrDefault()或其他函数。 I am looking for a function can get most presented items from a List.
我正在寻找一个可以从列表中获取最多显示项目的函数。
For example: 例如:
{ "a" , "a" , "a" , "b" }.MostPresents() => "a"
Is there a default function in c# (asp.net 4.0) for this? 在C#(asp.net 4.0)中是否有默认功能?
Is there a default function in c# (asp.net 4.0) for this?
在C#(asp.net 4.0)中是否有默认功能?
No, but you can slap together some LINQ and get it pretty quickly. 不,但是您可以将一些LINQ拍打在一起,并很快得到它。
var mostFrequent = sequence.GroupBy(x => x)
.Select(g => new { g.Key, Count = g.Count() })
.MaxBy(x => x.Count)
.Key;
var MostCommonItem = list.GroupBy(item => item)
.OrderByDescending(g => g.Count())
.Select(g => g.Key).First();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.