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,
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.
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.
//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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With