1
List<int> lstNumbers = new List<int>();

List of numbers which is instanciated by a streamreader

private void GetMode()
        {
            lblMode.Text +=  //How do I determine the mode of the data
        }

Sorry, This is really something stupid... Can anyone help me please

Kevin DiTraglia
  • 24,092
  • 16
  • 88
  • 134
user1659535
  • 19
  • 1
  • 2

2 Answers2

1

from http://www.remondo.net/calculate-mean-median-mode-averages-csharp/

public static IEnumerable<double> Modes(this IEnumerable<double> list)
    {
        var modesList = list
            .GroupBy(values => values)
            .Select(valueCluster =>
                    new
                        {
                            Value = valueCluster.Key,
                            Occurrence = valueCluster.Count(),
                        })
            .ToList();

        int maxOccurrence = modesList
            .Max(g => g.Occurrence);

        return modesList
            .Where(x => x.Occurrence == maxOccurrence && maxOccurrence > 1) // Thanks Rui!
            .Select(x => x.Value);
    }
}
hometoast
  • 10,977
  • 4
  • 37
  • 57
  • 1
    If you use the MoreLinq `MaxBy` method you can simplify all of the code after the GroupBy, and reduce it from making two passes to one. – Servy Sep 10 '12 at 14:34
0

since it sounds as a student question and language is C# I would expect LINQ queries being out of possibility (though question itself must state it). for LINQ queries though look at another answer. I am providing a do-it-yourself kind of answer (which should not be used in real-world programming).

class Program
{
    static void Main(string[] args)
    {
        var listOfInt = new List<int> {7, 4, 2, 5, 7, 5, 4, 3, 4, 5, 6, 3, 7, 5, 7, 4, 2};

        var histogram = BuildHistogram1(listOfInt);

        var modeValue = FindMode(histogram);

        Console.WriteLine(modeValue);
    }

    private static int FindMode(Dictionary<int, int> histogram)
    {
        int mode = 0;
        int count = 0;
        foreach (KeyValuePair<int, int> pair in histogram)
        {
            if( pair.Value>count)
            {
                count = pair.Value;
                mode = pair.Key;
            }
        }
        return mode;
    }

    private static Dictionary<int,int> BuildHistogram1(List<int> listOfInt)
    {
        var histogram = new Dictionary<int, int>();
        foreach (var v in listOfInt)
        {
            if (histogram.ContainsKey(v))
                histogram[v] = histogram[v] + 1;
            else
                histogram[v] = 1;
        }
        return histogram;
    }
}

it uses Dictionary to build a histogram. However plain array may be used for the same purpose if you know value range a head of time and it is narrow enough.

aiodintsov
  • 2,405
  • 12
  • 16