Sorting the dictionary <int, List <int>> by keys + values ​​inside the list

Assume that a

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

I want to output a sorted version, ordered first by keys and then by values ​​inside the list.

eg.

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

becomes

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

I tried to do this inside foreach, but obviously it is a bad idea to change what you iterate.

+5
source share
4 answers

Try the following:

    // 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);
        }
    }
+10
source

A Dictionaryis unsorted. To sort the dictionary, you can use OrderedDictionary.

To sort the lists you can use List<T>.OrderBy()

+3
source

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)});

Of course, this is pretty ugly. The best option at this stage is to use LINQ syntax

            var orderedItems =from pair in dictionary
                  orderby pair.Key
                  let values = pair.Value.OrderBy(i => i)
                  select new { Key = pair.Key, Value = values };

If you need to use the resulting IEnumerable as a list or array, you can create it using ToList or ToArray. In most cases, you can simply use IEnumerable as it

+3
source

You can move dictionary items and sort each list separately. it will look like this:

SortDictionary (dictionary);

thereafter:

foreach (System.Collections.Generic.KeyValuePair<int,IList<int>> list in dictionary)
        { 
            SortDictionary( list.Value)
        }
0
source

All Articles