How to use custom IComparer for SortedDictionary?

前端 未结 2 653
不思量自难忘°
不思量自难忘° 2021-01-11 17:30

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 t

相关标签:
2条回答
  • 2021-01-11 17:34

    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;
    

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

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

    0 讨论(0)
  • 2021-01-11 17:37

    Well, I haven't taken apart your comparer - but it looks like it's just comparing by last name, and you're trying to add the same last name (johansson) twice. That should give you an ArgumentException.

    What did you want to happen - and what do you want your comparer to do?

    Perhaps you want to sort by last name and then first name? That way you can have two email addresses with the same last name but different first names, and have them still be in the dictionary together, ordered by first name.

    0 讨论(0)
提交回复
热议问题