Reputation: 335
I am trying to get an average of occurrences of a string in a list. Basically I am trying to get the most common occurring string in a list of about 4 options. So for instance in this example
List<string> lMyList = new List<string>();
lMyList.Add("One");
lMyList.Add("One");
lMyList.Add("Two");
lMyList.Add("Two");
lMyList.Add("Two");
lMyList.Add("Three");
lMyList.Add("Three");
I want to get "Two" returned to me...
Any ideas?
Upvotes: 2
Views: 1336
Reputation: 22555
for finding average do:
list.GroupBy(x => x).Average(x=>x.Count())
for finding max do:
var max = groups.OrderbyDescending(x=>x.Count()).FirstOrDefault();
Upvotes: 2
Reputation: 17568
string most = lMyList.GroupBy(x => x)
.Select(g => new {Value = g.Key, Count = g.Count()})
.OrderByDescending(x=>x.Count).First();
Upvotes: 3
Reputation: 887469
You can use LINQ:
list.GroupBy(s => s).OrderByDescending(g => g.Count()).First()
Upvotes: 4