A simple LINQ question in C #

I am trying to use LINQto return an element that occurs with the 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 will return cherryas the maximum element, and 3- as the number of times when it happened. I would also like to split them into two requests, if necessary (i.e. receive the first request cherry, and the second - return the counter 3.

+5
source share
8 answers
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 if we do not like O(N log N):

var topWordGroup = words.GroupBy(word => word).Aggregate((current, acc) => current.Count() < acc.Count() ? acc : current);
+8
source

, , O(n log n). a 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
);

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

, (, , )

var item = words.GroupBy(x => x).OrderByDescending(x => x.Count()).First()
//item.Key is "cherry", item.Count() is 3

: op count

+4
string[] words = { "cherry", "apple", "blueberry", "cherry", "cherry", "blueberry" };

var topWordAndCount=words
    .GroupBy(w=>w)
    .OrderByDescending(g=>g.Count())
    .Select(g=>new {Word=g.Key,Count=g.Count()})
    .FirstOrDefault();

//if(topWordAndCount!=null)
//{
//    topWordAndCount.Word
//    topWordAndCount.Count
+1
string[] words = { "cherry", "apple", "blueberry", "cherry", "cherry", "blueberry" };

var r = words.GroupBy (x => x)
             .OrderByDescending (g => g.Count ())
             .FirstOrDefault ();
Console.WriteLine (String.Format ("The element {0} occurs {1} times.", r.Key, r.Count ()));
0

O (n):

var groups = words.GroupBy(x => x);
var max = groups.Max(x => x.Count());
var top = groups.First(y => y.Count() == max).Key;
0

O (n) (!):

s.GroupBy(x => x).Aggregate((IGrouping<string,string>)null, (x, y) =>  (x != null && y != null && x.Count() >= y.Count()) || y == null ? x : y, x => x);

:

s.GroupBy(x => x).Select(x => new { Key = x.Key, Count = x.Count() }).Aggregate(new { Key = "", Count = 0 }, (x, y) => x.Count >= y.Count ? x : y, x => x);
0

All Articles