c# - 如何遍历字典并比较值?

The*_*man 0 c# dictionary

我正在教自己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);
                }
        }
Run Code Online (Sandbox Code Playgroud)

我不确定是否使用索引来使用密钥进行比较,或者是否有其他方法来执行此操作,就像我上面尝试过的那样,使用foreach循环

Jon*_*eet 5

我当然不会使用当前的方法,说实话 - 你做的工作比你需要的要多得多.LINQ为您提供了比这更好的工具.您可以使用GroupBy它来使它更干净:

var pairs = array.GroupBy(x => x)
                 .Select(g => new { Key = g.Key, Count = g.Count() }
                 .OrderByDescending(pair => pair.Count)
                 .ToList();
Run Code Online (Sandbox Code Playgroud)

这将获得所有的键/计数对,最常见的是.然后显示部分应该相当简单,例如

// 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);
}
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,上面的代码替换了你问题中的所有代码.你根本不需要Dictionary<,>.