如何对SortedDictionary使用自定义IComparer? [英] How to use custom IComparer for SortedDictionary?

查看:422
本文介绍了如何对SortedDictionary使用自定义IComparer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难将自己的自定义IComparer用于我的SortedDictionary<>.目的是将电子邮件地址以特定格式(firstnam.lastname@domain.com)作为关键字,并按姓氏排序. 当我做这样的事情时:

I am having difficulties to use my custom IComparer for my SortedDictionary<>. The goal is to put email addresses in a specific format (firstnam.lastname@domain.com) 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("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.键.

I get this ArgumentException: An entry with the same key already exists. when adding the second item.

以前我没有为SortedDictionary使用自定义IComparer,但是我看不到自己的错误,我在做什么错了?

I haven't worked with a custom IComparer for a SortedDictionary before, and I fail to see my error , what am I doing wrong?

推荐答案

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

If the 2 lastNames are equal then compare for example the whole email like:

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

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

Actually, sorteddictionary comparison is also used to distinguish amongst keys* , so you must specify a complete comparison (not only your sorting strategy)

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

* I mean in sortedDictionary 2 keys are equal if Comparer gives 0

这篇关于如何对SortedDictionary使用自定义IComparer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆