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

由流式阅读器实例化的数字列表

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

对不起,这真的很愚蠢......谁能帮助我

4

2 回答 2

1

来自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);
    }
}
于 2012-09-10T14:24:53.753 回答
0

因为这听起来像是一个学生问题,而语言是 C#,所以我希望 LINQ 查询是不可能的(尽管问题本身必须说明它)。对于 LINQ 查询,请查看另一个答案。我正在提供一种自己动手做的答案(不应该在现实世界的编程中使用)。

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;
    }
}

它使用 Dictionary 来构建直方图。但是,如果您提前知道值范围并且足够窄,则可以将普通数组用于相同目的。

于 2012-09-10T14:49:43.613 回答