I have implemented the IComparable interface on my Student class, and I am trying to get the min and max Age of the students in the list. I am getting max value correctly but not min value. What am I missing in the code?
I am not sure whether Linq MAX and MIN methods gives correct results on the list of class which implements IComparable. When I run the below code I get Max Age = 31, Min age = 20 (but it should be 17)
public class Program
{
public static void Main()
{
IList<Student> stuList = new List<Student>(){
new Student(){StudentID=1,StudentName="Mike",Age=20},
new Student(){StudentID=2,StudentName="Nick",Age=24},
new Student(){StudentID=3,StudentName="Mary",Age=21},
new Student(){StudentID=4,StudentName="John",Age=17},
new Student(){StudentID=5,StudentName="Dave",Age=29},
new Student(){StudentID=6,StudentName="Don",Age=31}
};
Console.WriteLine("Total Students: "+stuList.Count());
var maxstud = stuList.Max();
var minstud = stuList.Min();
Console.WriteLine("Max Age: "+ maxstud.Age);
Console.WriteLine("Min Age: "+ minstud.Age);
}
}
public class Student : IComparable<Student>
{
public int StudentID {get;set;}
public string StudentName {get;set;}
public int Age {get;set;}
public int CompareTo(Student other)
{
if(this.Age >= other.Age)
{
return 1;
}
else
return 0;
}
}
If I use lambda exp I am getting correct min value:
Console.WriteLine("Min Age: "+ stuList.Min(s=>s.Age));// Min age =17
Your CompareTo implementation is not correct, it should return a value lower than 0 in certain cases.
The implementation of the
CompareTo(T)method must return anInt32that has one of three values, as shown in the following table.Less than zero This object precedes the object specified by the
CompareTomethod in the sort order.Zero This current instance occurs in the same position in the sort order as the object specified by the
CompareTomethod argument.Greater than zero This current instance follows the object specified by the
CompareTomethod argument in the sort order.
The easiest way to do that would be to do this:
public int CompareTo(Student other)
{
return this.Age.CompareTo(other.Age);
}
Don't reinvent the wheel, use the CompareTo already implemented by the framework on the Age property.
public int CompareTo(Student other)
{
return this.Age.CompareTo(other.Age);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With