I have a Sorted Dictionary that I want to Sort By Key Length.
Dictionary is defined as:
private SortedDictionary<String, String> _replacementDictionary;
and initialised as:
_replacementDictionary = new SortedDictionary<string, string>(new LengthComparer());
I thought I could use a Custom Sort like this:
class LengthComparer : IComparer<String>
{
public int Compare(string x, string y)
{
return x.Length.CompareTo(y.Length);
}
}
But this doesn't work for keys that are the same length. i.e. If I add keys "abc" and "xyz", only one of these shows when I enumerate the dictionary
If you mean you want to sort by length, then the key itself as a string, try:
class LengthComparer : IComparer<String>
{
public int Compare(string x,string y)
{
int lengthComparison=x.Length.CompareTo(y.Length)
if(lengthComparison==0)
{
return x.CompareTo(y);
}
else
{
return lengthComparison;
}
}
}
What this code does is this: It makes a comparison based on length. If the two strings are tied for length, then it resolves the tie by comparing the strings themselves, not their length. You need to resolve this tie because of the reason @Adriano gave in his comment.