假设我们有一个排序一个字典<INT,列表<int>>通过按键内部列表+值
var dictionary= new Dictionary<int, IList<int>>();
我要的是输出中它的排序版本,首先下令键,然后按值内一个列表。
例如,
1 2, 1, 6
5 2, 1
2 1, 3
变为
1 1, 2, 6
2 1, 3
5 1, 2
我试着做这里面foreach
,但显然这是一个坏主意,改变你迭代的东西。
假设我们有一个排序一个字典<INT,列表<int>>通过按键内部列表+值
var dictionary= new Dictionary<int, IList<int>>();
我要的是输出中它的排序版本,首先下令键,然后按值内一个列表。
例如,
1 2, 1, 6
5 2, 1
2 1, 3
变为
1 1, 2, 6
2 1, 3
5 1, 2
我试着做这里面foreach
,但显然这是一个坏主意,改变你迭代的东西。
试试这个:
// 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);
}
}
这是错误的,原因有两个。一,把它们放回字典中,你再次破坏他喜欢的订单。二,你不能将'IOrderedEnumerable
的确,我们错过了ToList调用。订单保持不变。 – Schiavini 2014-05-20 08:28:15
好。但是,最后通过调用“ToDictionary”,可以将项目放回无序集合中。 “工作”部分是巧合的,没有记录。实施可能会改变。需要记住的是**字典按定义是无序集合**。 [见](http://stackoverflow.com/questions/1453190/does-the-enumerator-of-a-dictionarytkey-tvalue-return-key-value-pairs-in-the) – nawfal 2014-05-20 08:33:10
A Dictionary
未排序。要对字典进行排序,您可以使用OrderedDictionary
。
要对列表排序,你可以使用List<T>.OrderBy()
这将解决只按键部分排序,不是吗? – 2012-02-14 12:41:12
-1:不回答问题,再读一遍。 OP不想对字典进行排序,他/她只想输出它。 – leppie 2012-02-14 12:41:50
@leppie我再读一遍。 OP还明确表示他/她想要一个“分类版本”。一本字典的排序版本是,好吧,去猜测。无论如何感谢downvote。 – 2012-02-14 12:46:59
可以遍历字典项目和seperately排序每个列表。它看起来像这样:
SortDictionary(dictionary);
后:
foreach (System.Collections.Generic.KeyValuePair<int,IList<int>> list in dictionary)
{
SortDictionary(list.Value)
}
您可以使用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)});
。当然,这是相当丑陋。在这一点上更好的选择是使用LINQ语法
var orderedItems =from pair in dictionary
orderby pair.Key
let values = pair.Value.OrderBy(i => i)
select new { Key = pair.Key, Value = values };
如果需要使用产生的IEnumerable列表或数组,您可以创建使用ToList或ToArray的一个。在大多数情况下,你可以直接使用IEnumerable,因为它是
“我想要得到的是一个有序的版本” - _how_你想要它吗?作为输出,还是作为一个新的集合? – 2012-02-14 12:42:27
编辑问题 – 2012-02-14 12:45:28