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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With