I have this class on my c# console application
public class Person
{
public Person(int id , string l, string f)
{
FirstName = f;
LastName = l;
Id = id;
}
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
}
In my Main method I have the following code:
public static void Main(string[] args)
{
Person[] p = new Person[3];
p[0] = new Person(8,"John", "Doe");
p[1] = new Person(9,"Adam", "Cas");
p[2] = new Person(1,"Oliver", "Anderson");
Array.Sort(p); // this doesn't work, i get InvalidOperationException
}
If it is array of simple types like string , int,..etc i can easily use Array.Sort(myarray)
and then it will be sorted.But when i use Array.Sort(p)
i get an exception (InvalidOperationException
).
Indeed this is expected exception as documentation on Array.Sort says
InvalidOperationException One or more elements in array do not implement the
IComparable
interface.
Unfortunately all samples show how to implement IComparer
for string while I need to be able to sort by a string property of the object ( Id, FirstName, LastName ). And there is no sample of IComparable
which my objects presumably need to imlement.
Here is a sample from the documentation:
public class ReverseComparer : IComparer
{
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
public int Compare(Object x, Object y)
{
return (new CaseInsensitiveComparer()).Compare(y, x );
}
}
There are indeed samples of IComparer
(like Using IComparer for sorting) but they show IComparer<T>
... There is also sample of IComparable
is corresponding documentation IComparable but that one is for temperature with non-string properties.