Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the mode of a list<double>?

Tags:

c#

I have a list:

List<double> final=new List<double>();
final.Add(1);
final.Add(2);
final.Add(3);

What sort of method could I use to find the mode of this list? Also, if there are two modes, the function would return the smaller of the two.

like image 934
Edward Karak Avatar asked Oct 19 '13 15:10

Edward Karak


People also ask

How do you find the mode in a list?

Mode is that number in the list which occurs most frequently. We calculate it by finding the frequency of each number present in the list and then choosing the one with highest frequency.

What is the mode if all numbers appear twice?

If there are two numbers that appear most often (and the same number of times) then the data has two modes. This is called bimodal.

Can a list have 2 modes?

More about modesThere can be more than one mode in a list or set of numbers. Look at this list of numbers: 1, 1, 1, 3, 3, 3. In this list there are two modes, because both 1 and 3 are repeated same number of times.


1 Answers

int? modeValue =
 final
 .GroupBy(x => x)
 .OrderByDescending(x => x.Count()).ThenBy(x => x.Key)
 .Select(x => (int?)x.Key)
 .FirstOrDefault();

All it takes are a few composed LINQ operations. You can also express the same with query expressions.

If the list is empty, modeValue will be null.

like image 129
usr Avatar answered Sep 18 '22 14:09

usr