Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 649
kovac Avatar asked Jun 27 '26 04:06

kovac


1 Answers

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" }
        }
    }
};
like image 198
CodeCaster Avatar answered Jun 29 '26 18:06

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!