繁体   English   中英

如何在C#中订购字典?

[英]How can I order a Dictionary in C#?

编辑:谢谢杰森,这是一本字典并不重要。 我只是希望运行时具有较低的运行时间。 LINQ方法快吗? 另外,我知道这不是主题,但n => n是什么意思?

我有一个数字列表,我想制作另一个列表,其中包含最开头和最少的数字。

所以我做的是通过列表并检查数字x是否在字典中。 如果不是那么我将密钥x和值1设为一个。 如果是那时我将值更改为值加1。

现在我想订购字典,这样我就可以列出一个列表,其中包含开头最多但最后最少的列表。

我怎么能在C#中做到这一点? PS。 运行时非常重要。

所以听起来你有一个Dictionary<int, int> ,其中键表示Dictionary<int, int>中的某个整数,相应的值表示整数出现次数的计数。 您是说要按频率按降序排序的计数来订购密钥。 然后你可以说

// dict is Dictionary<int, int>
var ordered = dict.Keys.OrderByDescending(k => dict[k]).ToList();

现在,听起来你开始使用List<int> ,这是你想要计算的值和按计数排序。 您可以在LINQ中快速执行此操作,如下所示:

// list is IEnumerable<int> (e.g., List<int>)
var ordered = list.GroupBy(n => n)
                  .OrderByDescending(g => g.Count())
                  .Select(g => g.Key)
                  .ToList();

或者在查询语法中

var ordered = (from n in list
               group n by n into g
               orderby g.Count() descending
               select g.Key).ToList();

现在,如果您需要拥有中间字典,您可以说

var dict = list.GroupBy(n => n)
               .ToDictionary(g => g.Key, g => g.Count());
var ordered = dict.Keys.OrderByDescending(k => dict[k]).ToList();

提供的信息如下: http//www.dotnetperls.com/sort-dictionary

Dictionary没有Sort方法。 如果我们需要按排序顺序遍历Dictionary内容,我们必须分别获取元素并对它们进行排序。 这是通过Keys和Values属性以及List实例完成的。

排序键

此示例通过使用Dictionary实例上的Keys属性,然后使用ToList扩展方法和Sort实例方法来解决此问题。

首先,创建一个示例Dictionary,并使用Add方法填充; 接下来,在Keys上使用ToList和Sort方法; 最后,使用foreach-loop构造循环生成的List。 另外,请注意如何在整个过程中使用var隐式类型关键字,以减少语法冗余。

在Dictionary [C#]中对键进行排序的程序

 using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Create dictionary and add five keys and values. var dictionary = new Dictionary<string, int>(); dictionary.Add("car", 2); dictionary.Add("apple", 1); dictionary.Add("zebra", 0); dictionary.Add("mouse", 5); dictionary.Add("year", 3); // Acquire keys and sort them. var list = dictionary.Keys.ToList(); list.Sort(); // Loop through keys. foreach (var key in list) { Console.WriteLine("{0}: {1}", key, dictionary[key]); } } } 

产量

 apple: 1 car: 2 mouse: 5 year: 3 zebra: 0 

排序值

接下来,我们将展示如何对Dictionary中的值进行排序。 我们看到一个可以在Visual Studio中编译并运行的控制台程序。 它为Dictionary添加了键,然后按其值对它们进行排序。 请记住,Dictionary实例最初不以任何方式排序。 我们在查询语句中使用LINQ orderby关键字。

对字典[C#]进行排序的OrderBy子句程序

 using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // Example dictionary. var dictionary = new Dictionary<string, int>(5); dictionary.Add("cat", 1); dictionary.Add("dog", 0); dictionary.Add("mouse", 5); dictionary.Add("eel", 3); dictionary.Add("programmer", 2); // Order by values. // ... Use LINQ to specify sorting by value. var items = from pair in dictionary orderby pair.Value ascending select pair; // Display results. foreach (KeyValuePair<string, int> pair in items) { Console.WriteLine("{0}: {1}", pair.Key, pair.Value); } // Reverse sort. // ... Can be looped over in the same way as above. items = from pair in dictionary orderby pair.Value descending select pair; } } 

产量

 dog: 0 cat: 1 programmer: 2 eel: 3 mouse: 5 

降序关键字

降序排序

 var items = from pair in dictionary orderby pair.Value descending select pair; 

示例输出

 mouse: 5 eel: 3 programmer: 2 cat: 1 dog: 0 

使用IEnumerable()上的GroupBy扩展名对数字进行分组并提取每个数字的计数。 这将从列表中创建字典并在一个语句中对其进行排序。

var ordered = list.GroupBy( l => l )
                  .OrderByDescending( g => g.Count() )
                  .ToDictionary( g => g.Key, g.Count() );
    List<KeyValuePair<type, type>> listEquivalent = 
new List<KeyValuePair<type, type>>(dictionary);    

    listEquivalent.Sort((first,second) =>
            {
                return first.Value.CompareTo(second.Value);
            });

也许这样的事情?

编辑:感谢Jason关于我遗漏的通知

您也可以考虑使用SortedDictionary。

它在插入时根据键对项目进行排序。 更多..

暂无
暂无

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

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