11

我在为我的 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,我看不到我的错误,我做错了什么?

4

2 回答 2

6

如果 2 个姓氏相等,则比较整个电子邮件,例如:

int comp = xLastname.CompareTo(yLastname);
if (comp == 0)
   return x.CompareTo(y);
return comp;

实际上, sorteddictionary 比较也用于区分 keys* ,因此您必须指定完整的比较(不仅是您的排序策略)

编辑:*我的意思是在 sortedDictionary 中,如果 Comparer 给出 0,则 2 个键相等

于 2010-04-27T09:28:50.123 回答
1

好吧,我没有拆开你的比较器 - 但它看起来只是按姓氏比较,而你试图添加相同的姓氏 (johansson) 两次。那应该给你一个ArgumentException.

想要发生什么——你想要你的比较器做什么?

也许您想先按姓氏排序,然后按名字排序?这样,您可以拥有两个姓氏相同但名字不同的电子邮件地址,并且它们仍然一起在字典中,按名字排序。

于 2010-04-27T09:26:57.747 回答