如何使用CustomedDictionary的自定义IComparer?

Mag*_*son 11 c# icomparer sorteddictionary

我很难将自定义IComparer用于我的SortedDictionary <>.目标是将电子邮件地址以特定格式(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);
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到这个ArgumentException: An entry with the same key already exists.添加第二个项目时.

我之前没有使用过SortedDictionary的自定义IComparer,我没有看到我的错误,我做错了什么?

dig*_*All 5

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

int comp = xLastname.CompareTo(yLastname);
if (comp == 0)
   return x.CompareTo(y);
return comp;
Run Code Online (Sandbox Code Playgroud)

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

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