假设我们有一个
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);
}
}
关于c# - 按键 + 列表中的值对 Dictionary<int, List<int>> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9276983/