Click here to Skip to main content
15,920,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to find a mode of given array: [2,2,3,3,4,5]

Now thing is there's actually two most frequently occurs elements in the array which is 2,3 so the output should be
2 3
but my solution only provides one mode of the array which is 2.
Now my question is: How do I find multiple mode in array?

What I have tried:

int mode_val = values.GroupBy(v => v).OrderByDescending(g => g.Count()).First().Key;
Posted
Updated 20-Sep-22 9:31am
v2
Comments
Member 15627495 20-Sep-22 9:45am    
it's LINQ ( to entities )

try :
int mode_val = values.GroupBy(v => v).OrderByDescending(g => g.Count()).all().Key;
Dan Sep2022 20-Sep-22 10:02am    
"No overload for method 'All' takes 0 arguments" Why did this ocurrs?

1 solution

My suggestion is to group the array contents then sort the resulting group collection by the group.Count(). From the sorted groups select a collection of tuples of type (int Key,int Count).Use TakeWhile to select only the tuples that have the highest count value. Foreach key in the selection, write the value out to the console.

C#
static void Main()
   {
      int[] collection = new[] { 2, 2, 3, 3, 4, 5 };
      var tuples = collection.GroupBy(n => n)
                   .OrderByDescending(group => group.Count())
                    //select a collection of tuples (int Key,int Count)
                   .Select(group => (Key: group.Key, Count: group.Count())).ToArray();
      var selection = tuples.TakeWhile(x => x.Count == tuples[0].Count);
      foreach (var (Key, Count) in selection)
       {

         Console.WriteLine(Key);
       }
   }

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900