如何遍历字典并比较值
本文关键字:字典 比较 遍历 何遍历 | 更新日期: 2023-09-27 18:14:29
我正在自学c#,并在做我自己的小项目。程序用随机数填充数组,程序返回数字(0-15)及其在数组中出现的次数。我将这些值存储在字典中,因为我想对值进行排序,而不会丢失映射到它的键。
排序后的值然后存储到另一个字典中,现在我希望能够遍历字典并获得具有最高值的键。换句话说,将出现次数最多的数字打印到控制台。在对字典进行排序时,最后一个数字将是最大值。
然而,可能有不止一个数字出现最多,这就是我卡住的地方。如果数字4,5,6,7都出现的次数最多,我希望能够将其打印到控制台。
Dictionary<int, int> dic = new Dictionary<int, int>();
//iterates through numbers 0-15
for (int y = 0; y <= 15; y++)
{
int m = 0;
//iterates through entire array
for (int i = 0; i < Arr.Length; i++)
{
//comparisons
if (y == Arr[i])
{
m++;
}
}
//Inserts number and count into the dictionary
dic.Add(y,m);
}
//Sorts the dictionary and adds the sorted one into a new dictionary
Dictionary<int, int> dic2 = new Dictionary<int, int>();
foreach (KeyValuePair<int, int> value in dic.OrderBy(key => key.Value))
{
Console.WriteLine("{0} appears {1} times ", value.Key, value.Value);
dic2.Add(value.Key, value.Value);
}
//Finds the keys with most common occurance
KeyValuePair<int, int> e = dic2.Last();
foreach (KeyValuePair<int, int> comp in dic2)
{
if (dic.Last() == dic[comp])
{
//something goes here
Console.WriteLine("Most common number is {0}", e.Key);
}
}
我不确定是否使用索引来比较使用键,或者是否有另一种方法来做到这一点,就像我上面尝试过的,使用foreach循环
老实说,我根本不会使用当前的方法——您做的工作比需要做的要多得多。LINQ为您提供了比这更好的工具。您可以使用GroupBy
使其更简洁:
var pairs = array.GroupBy(x => x)
.Select(g => new { Key = g.Key, Count = g.Count() }
.OrderByDescending(pair => pair.Count)
.ToList();
得到所有键/计数对,最频繁的先。然后显示部分应该相当简单,例如
// Note: this relies on the initial array being non-empty
var highestCount = pairs.First().Count;
foreach (var pair in pairs.TakeWhile(pair => pair.Count == highestCount))
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Count);
}
为了清楚起见,上面的代码替换了问题中的所有代码。你根本不需要Dictionary<,>
。
您可以使用linq查询来查找每个键的货币数量并对其进行计数。之后,返回一个带有Key和total的匿名对象,例如:
var q = from k in dic
let t = dic.Count(x => x.Value == k.Key)
select new { Key = k.Key, Total = t };
var max = q.OrderByDescending(x => Total).First();
Console.WriteLine("Most common number is {0} with {1} ocurrencies", max.Key, max.Total);