按列+内的键+值对Dictionary <int,List <int >>进行排序

Yur*_*han 5 .net c# linq

假设我们有一个

var dictionary= new Dictionary<int, IList<int>>();
Run Code Online (Sandbox Code Playgroud)

我想要的是输出它的排序版本,首先按键排序,然后按列表中的值排序.

例如

1   2, 1, 6
5   2, 1
2   1, 3
Run Code Online (Sandbox Code Playgroud)

1    1, 2, 6
2    1, 3
5    1, 2
Run Code Online (Sandbox Code Playgroud)

我尝试在里面做foreach,但显然改变你正在迭代的东西是个坏主意.

Sch*_*ini 11

试试这个:

    // 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)