是的,你是对的:
让我们有一个列表的数字:
List<int> myValues = new List<int>(new int[] { 1, 3, 3, 3, 7, 7 } );
你需要有一个循环遍历列表一次:
foreach (var val in myValues)
{
}
查看一个数字在数组中重复了多少次,以保存一个数字重复的次数:
Dictionary<int, int> repetitions = new Dictionary<int, int>();
foreach (var val in myValues)
{
if (repetitions.ContainsKey(val))
repetitions[val]++; // Met it one more time
else
repetitions.Add(val, 1); // Met it once, because it is not in dict.
}
现在,您的字典 repetitions 存储了 key 值重复的次数(确切地说是 value)。
然后,你需要找到模式的记录(即重复次数最多的记录(即最高值))并取这个。 LINQ 将帮助我们 - 让我们按值对数组进行排序并取最后一个……或者按降序排序并取第一个。实际上,就结果和生产力而言,这是相同的。
var modeRecord = repetitions.OrderByDescending(x => x.Value).First();
// or
var modeRecord = repetitions.OrderBy(x => x.Value).Last();
来了!这里我们有一个模式:
List<int> myValues = new List<int>(new int[] { 1, 3, 3, 3, 7, 7 } );
Dictionary<int, int> repetitions = new Dictionary<int, int>();
foreach (var val in myValues)
{
if (repetitions.ContainsKey(val))
repetitions[val]++; // Met it one more time
else
repetitions.Add(val, 1); // Met it once, because it is not in dict.
}
var modeRecord = repetitions.OrderByDescending(x => x.Value).First();
Console.WriteLine("Mode is {0}. It meets {1} times in an list", modeRecord.Key, modeRecord.Value);
您的模式计算逻辑很好。您所需要的只是在代码中按照自己的说明进行操作:)