对Dictionary <int,list <int =“”>&gt;进行排序按键+列表中的值</int,>

时间:2012-02-14 12:37:28

标签: c# .net linq

假设我们有一个

var dictionary= new Dictionary<int, IList<int>>();

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

E.g。

1   2, 1, 6
5   2, 1
2   1, 3

变为

1    1, 2, 6
2    1, 3
5    1, 2

我尝试在foreach内进行,但显然改变你正在迭代的东西是个坏主意。

4 个答案:

答案 0 :(得分: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);
        }
    }

答案 1 :(得分:3)

Dictionary未分类。要对字典进行排序,您可以使用OrderedDictionary

要对列表进行排序,您可以使用List<T>.OrderBy()

答案 2 :(得分:3)

您可以使用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

即可

答案 3 :(得分:0)

您可以遍历字典项并分别对每个列表进行排序。它看起来像这样:

SortedDictionary(字典);

之后:

foreach (System.Collections.Generic.KeyValuePair<int,IList<int>> list in dictionary)
        { 
            SortDictionary( list.Value)
        }
相关问题