내 SortedDictionary <>에 내 사용자 지정 IComparer를 사용하는 데 어려움이 있습니다. 목표는 전자 메일 주소를 특정 형식 ([email protected])으로 키로 지정하고 성으로 정렬하는 것입니다. 나는 이런 식으로 뭔가 할 때 는 :SortedDictionary에 대한 사용자 지정 IComparer를 사용하는 방법?
public class Program
{
public static void Main(string[] args)
{
SortedDictionary<string, string> list = new SortedDictionary<string, string>(new SortEmailComparer());
list.Add("[email protected]", "value1");
list.Add("[email protected]", "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로 작업하지 않았으며 오류가 표시되지 않습니다. 무엇이 잘못 되었나요?
감사. 이것은 단순하고 우아한 해결책이었습니다. –