Question

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!

Was it helpful?

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

OTHER TIPS

You can :

Create a class that encapsulates those keys and override the == operator, Object.Equals method and the Object.GetHashCode method. Also have the class implement the IComparable interface such that the rules for equality will automatically sort your keys the right way. Now you can simply place those keys in a SortedDictionary or SortedList and it will automatically sort the way you want.

OR

Implement an IComparer object that compares those strings the way you want, and specify the IComparer when constructing a SortedDictionaryor SortedList.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top