Search code examples
c#.netcomparison

Custom Sorting (IComparer on three fields)


I have a person class with three fields, Title, Name, Gender and I would like to create a Custom Sort for it to sort it first by Title, then by Name and then by Gender ascending:

public class SortPerson : IComparer
    {
        public int Compare(object x, object y)
        {
            (…)
        }
    }

I know how to do this for only one variable to compare against: But How would I have to proceed with three?

public class SortPerson : IComparer
        {

int IComparer.Compare(object a, object b)
   {
      Person p1=(Person)a;
      Person p2=(Person)b;
      if (p1.Title > p2.Title)
         return 1;
      if (p1.Title < p2.Title)
         return -1;
      else
         return 0;
   }
}

Many Thanks,


Solution

  • //Assuming all the fields implement IComparable
    int result = a.field1.CompareTo(b.field1);
    if (result == 0)
      result = a.field2.CompareTo(b.field2);
    if (result == 0)
      result = a.field3.CompareTo(b.field3);
    return result;