简体   繁体   English

CodeGo.net>如何遍历字典和比较值?

[英]c# - How to iterate through a dictionary and compare values?

I'm teaching myself c# and working on my own mini project. 我正在自学c#并从事自己的迷你项目。 The program populates an array with random numbers, the program returns the number (0-15) and the number of occurrences it appears in the array. 程序使用随机数填充数组,程序返回数字(0-15)以及它出现在数组中的出现次数。 I stored these values in a dictionary as I wanted to sort the values without losing the key mapped to it. 我想将这些值存储在字典中,因为我希望对这些值进行排序而不丢失映射到它的键。

The sorted values are then stored into another dictionary and now I want to be able to iterate through the dictionary and get the key with the highest value. 然后将排序后的值存储到另一个字典中,现在我希望能够遍历字典并获取具有最高值的键。 In other words print to the console the number with the most occurrences. 换句话说,将出现次数最多的数字打印到控制台。 As the dictionary is sorted, the last number will be the highest value. 在对字典进行排序时,最后一个数字将是最大值。

However there could be more than one number tied for the most occurrences and that's where I'm stuck on. 但是,最多出现的数字可能不止一个,这就是我要坚持的地方。 If the numbers 4,5,6,7 all appear the most number of times, i want to be able to print that to the console. 如果数字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);
                }
        }

I'm not sure whether to use indexes to compare using the key or if there is another way to do this like I have tried above, using a foreach loop 我不确定是使用索引还是使用键进行比较,或者是否有另一种方法(例如我上面尝试过的)使用foreach循环进行比较

I wouldn't use the current approach at all, to be honest - you're doing much more work than you need to. 老实说,我根本不会使用当前的方法-您要做的工作远远超出您的需要。 LINQ gives you much better tools than this. LINQ为您提供了比这更好的工具。 You can use GroupBy to make it all cleaner: 您可以使用GroupBy使其变得更加干净:

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

That gets you all the key/count pairs, most-frequent first. 这使您获得所有的键/计数对,最常见的是第一个。 The display part should then be reasonably simple, eg 显示部分应该相当简单,例如

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

Just to be clear, the code above replaces all the code in your question. 为了清楚起见,上面的代码替换了问题中的所有代码。 You don't need a Dictionary<,> at all. 您根本不需要Dictionary<,>

You could use a linq query to find the number of ocurrencies for each key and count it. 您可以使用linq查询来查找每个键的出现次数并进行计数。 After, return a anon object with the Key and total, for sample: 之后,返回带有Key和total的anon对象作为示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM