Jul 2, 2008

Comparing Custom Objects in C#

Once again I found myself trying to remember the specifics of how to compare specific attributes of a custom object when doing an Array Sort. The linked MS kb article has the specifics, but I'll copy some of that here, for longevity. ;)
private class sortYearAscendingHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
car c1=(car)a;
car c2=(car)b;
if (c1.year > c2.year)
return 1;
if (c1.year < c2.year)
return -1;
else
return 0;
}
}

The key is you have to return one of three values:
  • -1 if the first object is less than the second
  • 1 if the first object is greater than the second
  • 0 if the values of the two objects are equal
Hope this helps someone,
Ian

No comments: