Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Sorting (IComparer on three fields)

Tags:

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,

like image 733
Houman Avatar asked Dec 21 '10 16:12

Houman


People also ask

How to sort a list of objects c#?

C# has a built-in Sort() method that performs in-place sorting to sort a list of objects. The sorting can be done using a Comparison<T> delegate or an IComparer<T> implementation.

What is the difference between IComparable and IComparer?

IComparer compares two objects that it's given. IComparable is implemented by the object that is being compared, for the purpose of comparing with another one of itself.


1 Answers

//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; 
like image 144
Itay Karo Avatar answered Sep 30 '22 10:09

Itay Karo