Sorting an objects array in C#
If you want to sort an array of objects with the static method Sort of the Array class, it doesn't work without any problems...
If you sort an array of int, it's not a problem but let's imagine you have to sort an array of Student on their birthdate...
In fact it's very simple, your class have to implement the IComparable interface and the method CompareTo(object obj) that returns an int (integer):
- more than zero, if the instance is greater than obj,
- zero if the insance is equal to obj,
- less than zero if the instance is less than obj.
For the example of the Student class, you have to compare the birthdate of the instance with the birthdate of obj.
Please let's see how to build this class Student:
public class Student : IComparable
{
...
public int CompareTo(object obj)
{
{
if(obj is Student)
{
Student temp=(Student)obj;
//Comparaison on the birthdate field
//CompareTo return -1 if instance is less than obj, 0 if is equal and 1 if is greater
Student temp=(Student)obj;
//Comparaison on the birthdate field
//CompareTo return -1 if instance is less than obj, 0 if is equal and 1 if is greater
return _birthdate.CompareTo(temp._birthdate);
}
else
{
throw new ArgumentException("Object is not a Student");
}
}
...
}
}
else
{
throw new ArgumentException("Object is not a Student");
}
}
...
}
You can see that I make the comparaison on the _birthdate field (DateTime type) and also use the method CompareTo of the DateTime class.
Jay


0 Comments:
Post a Comment
<< Home