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

时间:2014-07-23 15:03:19

标签: 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);
                }
        }

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

2 个答案:

答案 0 :(得分:5)

我根本不会使用当前的方法,说实话 - 你做的工作比你需要的多得多。 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<,>

答案 1 :(得分:2)

您可以使用linq查询来查找每个键的出现次数并对其进行计数。之后,返回带有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);
相关问题