我试图用来LINQ返回一个发生最大次数的元素及其发生的次数.
例如:我有一个字符串数组:
string[] words = { "cherry", "apple", "blueberry", "cherry", "cherry", "blueberry" };
//...
Some LINQ statement here
//...
Run Code Online (Sandbox Code Playgroud)
在此数组中,查询将cherry作为发生的最大元素返回,并返回3它发生的次数.如果有必要,我也愿意将它们分成两个查询(即第一个查询获取cherry,第二个返回计数3.
jas*_*son 12
到目前为止提出的解决方案是O(n log n).这是一个O(n)解决方案:
var max = words.GroupBy(w => w)
.Select(g => new { Word = g.Key, Count = g.Count() })
.MaxBy(g => g.Count);
Console.WriteLine(
"The most frequent word is {0}, and its frequency is {1}.",
max.Word,
max.Count
);
Run Code Online (Sandbox Code Playgroud)
这需要定义MaxBy.这是一个:
public static TSource MaxBy<TSource>(
this IEnumerable<TSource> source,
Func<TSource, IComparable> projectionToComparable
) {
using (var e = source.GetEnumerator()) {
if (!e.MoveNext()) {
throw new InvalidOperationException("Sequence is empty.");
}
TSource max = e.Current;
IComparable maxProjection = projectionToComparable(e.Current);
while (e.MoveNext()) {
IComparable currentProjection = projectionToComparable(e.Current);
if (currentProjection.CompareTo(maxProjection) > 0) {
max = e.Current;
maxProjection = currentProjection;
}
}
return max;
}
}
Run Code Online (Sandbox Code Playgroud)
var topWordGroup = words.GroupBy(word => word).OrderByDescending(group => group.Count()).FirstOrDefault();
// topWordGroup might be a null!
string topWord = topWordGroup.Key;
int topWordCount = topWordGroup.Count;
Run Code Online (Sandbox Code Playgroud)
如果我们不喜欢O(N log N):
var topWordGroup = words.GroupBy(word => word).Aggregate((current, acc) => current.Count() < acc.Count() ? acc : current);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
994 次 |
| 最近记录: |