在C#中简单的LINQ问题 [英] Simple LINQ question in C#
本文介绍了在C#中简单的LINQ问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 LINQ
返回其发生的时间和最大数量发生的次数的一个元素。
例如: 我有一个字符串数组:
的String []字= {樱桃,苹果,蓝莓,樱花,樱花,蓝莓};
// ...
这里有些LINQ声明
// ...
在此阵列,查询将返回樱桃
作为最大发生的元素,而 3
的数量有时它发生。我也愿意将它们分成两个查询,如果这是必要的(即的第一次查询,以获得樱桃
,和第二返回计数 3
。
解决方案
VAR topWordGroup = words.GroupBy(字=>字).OrderByDescending(组=> group.Count( ))FirstOrDefault()。
// topWordGroup可能是空的!
字符串topWord = topWordGroup.Key;
INT topWordCount = topWordGroup.Count;
和的情况下,如果我们不喜欢 O(N日志N)
:
VAR topWordGroup = words.GroupBy(字=>字).Aggregate((电流,ACC)=> current.Count()< acc.Count()ACC : 当前);
I am trying to use LINQ
to return the an element which occurs maximum number of times AND the number of times it occurs.
For example: I have an array of strings:
string[] words = { "cherry", "apple", "blueberry", "cherry", "cherry", "blueberry" };
//...
Some LINQ statement here
//...
In this array, the query would return cherry
as the maximum occurred element, and 3
as the number of times it occurred. I would also be willing to split them into two queries if that is necessary (i.e., first query to get the cherry
, and second to return the count of 3
.
解决方案
var topWordGroup = words.GroupBy(word => word).OrderByDescending(group => group.Count()).FirstOrDefault();
// topWordGroup might be a null!
string topWord = topWordGroup.Key;
int topWordCount = topWordGroup.Count;
And in case if we don't like O(N log N)
:
var topWordGroup = words.GroupBy(word => word).Aggregate((current, acc) => current.Count() < acc.Count() ? acc : current);
这篇关于在C#中简单的LINQ问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文