[英]Sort a Dictionary<int, List<int>> by keys + values inside list
Suppose we have a 假设我们有一个
var dictionary= new Dictionary<int, IList<int>>();
What I want is to ouput a sorted version of it, ordered first by keys and then by values inside a list. 我想要的是输出它的排序版本,首先按键排序,然后按列表中的值排序。
Eg 例如
1 2, 1, 6
5 2, 1
2 1, 3
Becomes 变
1 1, 2, 6
2 1, 3
5 1, 2
I tried doing it inside foreach
, but obviously this is a bad idea to change the thing you are iterating. 我尝试在foreach
做到这一点,但显然改变你正在迭代的东西是个坏主意。
Try this: 试试这个:
// Creating test data
var dictionary = new Dictionary<int, IList<int>>
{
{ 1, new List<int> { 2, 1, 6 } },
{ 5, new List<int> { 2, 1 } },
{ 2, new List<int> { 2, 3 } }
};
// Ordering as requested
dictionary = dictionary
.OrderBy(d => d.Key)
.ToDictionary(
d => d.Key,
d => (IList<int>)d.Value.OrderBy(v => v).ToList()
);
// Displaying the results
foreach(var kv in dictionary)
{
Console.Write("\n{0}", kv.Key);
foreach (var li in kv.Value)
{
Console.Write("\t{0}", li);
}
}
A Dictionary
is unsorted. Dictionary
未分类。 To sort a dictionary you can use the OrderedDictionary
. 要对字典进行排序,您可以使用OrderedDictionary
。
To sort the lists, you can use List<T>.OrderBy()
要对列表进行排序,可以使用List<T>.OrderBy()
You can use LINQ to order the contents of the dictionary like this: 您可以使用LINQ来命令字典的内容,如下所示:
var dictionary = new Dictionary<int, IList<int>>();
var orderedItems = dictionary
.OrderBy(pair => pair.Key)
.Select(new {
Key = pair.Key,
Value = pair.Value.OrderBy(i => i)});
Of course, this is rather ugly. 当然,这是相当丑陋的。 A better option at this point is to use LINQ syntax 此时更好的选择是使用LINQ语法
var orderedItems =from pair in dictionary
orderby pair.Key
let values = pair.Value.OrderBy(i => i)
select new { Key = pair.Key, Value = values };
If you need to use the resulting IEnumerable as a list or array, you can create one using ToList or ToArray. 如果需要将生成的IEnumerable用作列表或数组,可以使用ToList或ToArray创建一个。 In most cases though, you can just use the IEnumerable as it is 但在大多数情况下,您可以按原样使用IEnumerable
You can loop through the dictionary items and sort each list seperately. 您可以遍历字典项并单独对每个列表进行排序。 it will look like this: 它看起来像这样:
SortDictionary(dictionary); SortDictionary(字典);
after that: 之后:
foreach (System.Collections.Generic.KeyValuePair<int,IList<int>> list in dictionary)
{
SortDictionary( list.Value)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.