【问题标题】:How to use custom IComparer for SortedDictionary?如何为 SortedDictionary 使用自定义 IComparer?
【发布时间】:2011-02-12 18:47:34
【问题描述】:

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

【问题讨论】:

    标签: c# icomparer sorteddictionary


    【解决方案1】:

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

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

    其实sorteddictionary比较也是用来区分keys*的,所以你必须指定一个完整的比较(不仅仅是你的排序策略)

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

    【讨论】:

    • 谢谢。这是简单优雅的解决方案。
    【解决方案2】:

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

    想要发生什么 - 你想要你的比较者做什么?

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

    【讨论】:

    • 确实,您的假设是正确的。 @digEmAll 提供了我想要的解决方案,@Foxfire 解释了原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2014-02-14
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多