The List.Sort() method knows how to sort any type or class that implements the
IComparable<T> interface. That interface has just one member—a method called
CompareTo(). Sort() uses an object’s CompareTo() method to compare it with
other objects, and uses its return value (an int) to determine which comes first.
e.g.
class Duck : IComparable<Duck> {
public int Size;
public KindOfDuck Kind;
public int CompareTo(Duck duckToCompare) {
if (this.Size > duckToCompare.Size)
return 1;
else if (this.Size < duckToCompare.Size)
return -1;
else
return 0;
}
}
List<Duck> ducks = new List<Duck>() {
new Duck() { Kind = KindOfDuck.Mallard, Size = 17 },
....
}
ducks.Sort();
Or you can use IComparer to tell your List how to sort, e.g.
class DuckComparerBySize : IComparer<Duck>
{ public int Compare(Duck x, Duck y)
{ if (x.Size < y.Size)
return -1;
if (x.Size > y.Size)
return 1;
return 0;
} }
DuckComparerBySize sizeComparer = new DuckComparerBySize();
ducks.Sort(sizeComparer);
Comments
Post a Comment