我在为我的 SortedDictionary<> 使用我的自定义 IComparer 时遇到了困难。目标是将电子邮件地址以特定格式(firstnam.lastname@domain.com)作为键,并按姓氏排序。当我做这样的事情时:
public class Program
{
public static void Main(string[] args)
{
SortedDictionary<string, string> list = new SortedDictionary<string, string>(new SortEmailComparer());
list.Add("a.johansson@domain.com", "value1");
list.Add("b.johansson@domain.com", "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);
}
}
我得到这个 ArgumentException:
An entry with the same key already exists.
添加第二项时。
我以前没有为 SortedDictionary 使用过自定义 IComparer,我看不到我的错误,我做错了什么?