IComparer - ошибка при сортировке - C#
Формулировка задачи:
Вообщем нужно создать сортировку. вот кусок кода
вызываю его вот так
И показывается вот такая ошибка :
IComparer (or the IComparable methods it relies upon) did not return zero when Array.Sort called x. CompareTo(x). x: '' x's type: 'TierDropDown' The IComparer: ''.
Вопрос, почему когда сортирует, он не понимает что вызвали один и тод же объект? и не пишет ноль? что не так в коде?
public int CompareTo(TierDropDown obj)
{
if (obj == null)
{
return 1;
}
else
{
if (this.Name.Equals(obj.Name))
{
return 0;
}
else
{
return this.Name.CompareTo(obj.Name);
}
}
}pResult.Sort();
Решение задачи: «IComparer - ошибка при сортировке»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication26
{
class Program
{
static void Main(string[] args)
{
List<MyClass> myList = new List<MyClass>()
{
new MyClass{ID=2, Name="One"},
new MyClass{ID=1, Name="Three"},
new MyClass{ID=0, Name="Two"}
};
Console.WriteLine("***** Unsorted List *****\n");
foreach(MyClass mc in myList)
{
Console.WriteLine(mc);
}
myList.Sort();
Console.WriteLine("\n****** Sorted List *****\n");
foreach (MyClass mc in myList)
{
Console.WriteLine(mc);
}
Console.ReadLine();
}
}
class MyClass:IComparable<MyClass>
{
public int ID { get; set; }
public string Name { get; set; }
public int CompareTo(MyClass other)
{
if (this.ID > other.ID)
return 1;
if (this.ID < other.ID)
return -1;
else
return 0;
}
public override string ToString()
{
return string.Format("ID: {0}, Name: {1}", ID, Name);
}
}
}