Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

.net - Simple LINQ question in C#

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solutions presented so far are O(n log n). Here's an O(n) solution:

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
);

This needs a definition of MaxBy. Here is one:

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;                
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...