Search code examples
c#.netasp.net-core-2.1

How to initialize a nested Sorted Dictionary with Comparer?


I want to create a dictionary of sorted dictionaries of which the sorted dictionaries arrange the keys in descending order. I'm trying like:

private readonly IDictionary<string, SortedDictionary<long, string>> myDict= new Dictionary<string, SortedDictionary<long, string>>();

How do I set the comparer like:

Comparer<long>.Create((x, y) => y.CompareTo(x))

for the nested dictionary?


Solution

  • With this code:

    var myDict = new Dictionary<string, SortedDictionary<long, string>>();
    

    You're initializing an empty dictionary, which doesn't contain any nested dictionaries. To do the latter:

    var comparer = Comparer<long>.Create((x, y) => y.CompareTo(x));
    
    var myDict = new Dictionary<string, SortedDictionary<long, string>
    {
        // Add a SortedDictionary to myDict
        { "dict1", new SortedDictionary<long, string>>(comparer) 
            {
                // Add a key-value pair to the SortedDictionary
                { 123, "nestedValue" }
            }
        }
    };