Search code examples
c#.net-4.0enumslogicsorteddictionary

Sorted Dictionary - C#


I'm trying to figure out how to create a sorted dictionary where the key is sorted in a non-alphabetical manner. Is there a way I can define the way I want it to sort?

For example, the keys might be in order like the following:

AAA1X
AAB1Y
AAC1Y
AAA2X
AAB2Y
AAC2X

Although the first three letters are alphabetical, if I sort as is it will lump them in the wrong order (due to the number). Also note, that there is either a X or Y at the end. In the code, there will only ever be an X or a Y.

Even if I can write an enumeration for the ordering of all possible combinations I'd be willing to do that as well, but I'm not sure how I can use the sorted dictionary and an enumeration...

I know this is a bit vague, but any help would be much appreciated!

Cheers!


Solution

  • One of the constructors for SortedDictionary<TKey, TValue> takes an IComparer<TKey>, where you can specify a custom comparer class that the dictionary will use for sorting.

    public class CustomComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            // do your own comparison however you like; return a negative value
            // to indicate that x < y, a positive value to indicate that x > y,
            // or 0 to indicate that they are equal.
        }
    }
    
    ...
    
    SortedDictionary<string, object> dict = 
                  new SortedDictionary<string, object>(new CustomComparer());