I'm wanting to create a IComparer<string>
for a SortedDictionary<string, int>
that will sort everything alphabetically but if it see a key of 'Other' it will put 'Other' at the end of the list.
Asked
Active
Viewed 70 times
0

vdh_ant
- 12,720
- 13
- 66
- 86
-
1A worthy goal. How is it coming? – Anthony Pegram Apr 11 '13 at 04:02
1 Answers
2
You mean like this?
public sealed class MyComparer : Comparer<string>
{
public override int Compare(string x, string y)
{
if(x == "Other")
return y == "Other" ? 0 : 1;
if(y == "Other")
return -1;
// Change this comparer if required.
return StringComparer.OrdinalIgnoreCase.Compare(x, y);
}
}
Usage:
var dict = new SortedDictionary<string, int> (new MyComparer())
{
{ "Other", 1 }, { "aaa", 2 }, { "bbb", 3 }
};
Obviously, you can make this more generic by writing a SpecialCaseAtEndComparer<T>
by:
- Allowing the "special" value to be injected into the comparer.
- Allowing the "normal" comparer to be injected into the comparer.
- Making the comparer work for all types, not just strings.

Ani
- 111,048
- 26
- 262
- 307