How to use custom IComparer for SortedDictionary?
Posted
by Magnus Johansson
on Stack Overflow
See other posts from Stack Overflow
or by Magnus Johansson
Published on 2010-04-27T09:22:53Z
Indexed on
2010/04/27
9:33 UTC
Read the original article
Hit count: 1026
I am having difficulties to use my custom IComparer for my SortedDictionary<>. The goal is to put email addresses in a specific format ([email protected]) as the key, and sort by last name. When I do something like this:
public class Program
{
public static void Main(string[] args)
{
SortedDictionary<string, string> list = new SortedDictionary<string, string>(new SortEmailComparer());
list.Add("[email protected]", "value1");
list.Add("[email protected]", "value2");
foreach (KeyValuePair<string, string> kvp in list)
{
Console.WriteLine(kvp.Key);
}
Console.ReadLine();
}
}
public class SortEmailComparer : IComparer<string>
{
public int Compare(string x, string y)
{
Regex regex = new Regex("\\b\\w*@\\b",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
string xLastname = regex.Match(x).ToString().Trim('@');
string yLastname = regex.Match(y).ToString().Trim('@');
return xLastname.CompareTo(yLastname);
}
}
I get this ArgumentException:
An entry with the same key already exists.
when adding the second item.
I haven't worked with a custom IComparer for a SortedDictionary before, and I fail to see my error , what am I doing wrong?
© Stack Overflow or respective owner