Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have an array of numbers created by the user, the array is sorted and I can find the Average, Median, Max, Min, Lowest -> Highest, Highest -> Lowest. Now I just need to find the mode. Here is the code I made that works if there is only 1 Mode, I need to make it work to find 3 modes .. I.e. if the array was [1,1,1,2,2,2,3,3,3,5,6] then the mode would be 1 , 2 , 3

    Dim countermode As Integer
    Dim w, s, r, i, p, tempmode As Integer
    p = 1

    For w = (x - 1) To 0 Step -1

        p += 1

        For s = (x - p) To 0 Step -1
            r = marks(w)
            i = marks(s)

            If i = r Then
                countermode += 1
                tempmode = marks(w)
            End If


    lblmode.Text = tempmode
share|improve this question
what is mode? it is related to the sorting logic. –  paritosh Dec 21 '12 at 16:09
@paritosh - Mode is the subset of numbers which appears the most frequently within a set. –  Bobson Dec 21 '12 at 16:20
A wonderful write-up on just this functionality in Linq can be found here: LinqMode –  dgp Feb 6 '13 at 15:28

1 Answer 1

In C#:

var list = arr.GroupBy(x => x)
              .Select(x => new { Count = x.Count(), Value = x.Key })
              .GroupBy(x => x.Count)
              .OrderByDescending(x => x.Key)

Automatically converted to VB.NET:

Dim list = arr.GroupBy(Function(x) x) _
              .[Select](Function(x) New With { _
                                    Key .Count = x.Count(), _
                                    Key .Value = x.Key _
                       }) _
              .GroupBy(Function(x) x.Count) _
              .OrderByDescending(Function(x) x.Key) _
              .First() _

You might want to make it more idiomatic.

share|improve this answer
Fascinating, +1 for the C# code, -1 for the VB code, that stuff is just plain horrible to look at and should not be. –  konijn Dec 21 '12 at 16:09
As I said, it was an automatic conversion. I didn't learn to work with LINQ until after I switched to c#, so I couldn't tell you what it should look like. –  Bobson Dec 21 '12 at 16:16
Edited to make it look cleaner, at the very least. –  Bobson Dec 21 '12 at 16:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.