c# - 按键 + 列表中的值对 Dictionary<int, List<int>> 进行排序

标签 c# .net linq

假设我们有一个

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/

相关文章:

C#、Linq2SQL - 获取具有关系数据的 ViewModel 对象的技巧?

javascript - block 范围声明...TypeScript 和 Asp.net MVC 5

c# - Linq 表达式 : Perform Distinct on a list dynamic property

.net - 单元测试中的代码覆盖率

linq - 构建动态表达式来比较两个表

c# - 如何按运行总数对对象列表进行分组?

c# - 使用 WiX 工具集编辑文件

c# - 两个 .Net 应用程序之间的高效通信

c# - 将变量从用户表单传递到类

c# - 如何让windows窗体只在主屏幕上打开