C#中简单的LINQ问题

Bre*_*ett 5 .net c# linq

我试图用来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)

  • 你也可以在必要时用`Aggregate`代替`MaxBy`,虽然`MaxBy`是**更好*:var max = words.GroupBy(x => x,(k,g)=> new {Word = k, Count = g.Count()}).Aggregate((a,x)=>(x.Count> a.Count)?x:a);` (2认同)

Sno*_*ear 8

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)

  • 当"O(n)"可能时,这是"O(n log n)":http://stackoverflow.com/questions/4888537/simple-linq-question-in-c/4888703#4888703. (2认同)