I wanted to make my Class Sortable(By Age) when it stored in List.
I read this : IComparable Vs IComparer and I maked my class Sortable .
public class Student : IComparable<Student>
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Student other)
{
if (this.Age > other.Age)
{
return 1;
}
else if (this.Age < other.Age)
{
return -1;
}
else
{
return 0;
}
}
}
List students = new List();
// And Filling students
students.Sort();
Now , I want to make my class Distinctable , I mean when I call .Distinct() it remove duplicate students By ID .
I read IEquatable VS IEqualityComparer And same as Sort ( That give no argumants ) I expect to call .Distinct() with no passing argumants.
public class Student : IEquatable<Student>
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool Equals(Student other)
{
if (this.ID == other.ID)
{
return true;
}
else
{
return false;
}
}
}
List students = new List();
// And Filling students
students.Distinct();
But when I use this nothing happened . WHY ?
And How can I implement IEquatable and use Distinct() with no passing argumants ?