I know how to pass Comparison to a Sort.
I want to compare two objects with Comparison. How can I do that?
The class already implements IComparible. This is for a custom comparison.
I know how to pass Comparison to a Sort.
I want to compare two objects with Comparison. How can I do that?
The class already implements IComparible. This is for a custom comparison.
Comparison is a delegate that defines how the comparison method should return and what parameters should receive. In this sample, it creates the method CompareDinosByLength to implement the Comparison delegate.
If you want to compare your objects you should implement your method in the following way:
public static int CompareObjects(MyClass a, MyClass b) {
if (a < b) { // Make your comparison logic here.
return -1;
} else if (a == b) {
return 0;
} else {
return 1;
}
}
The only restriction for creating this method is the returning value has to follow this pattern (-1 when x < y, 0 when x = y, +1 when x > y).
To add to the sort method, you only have to pass the method's name as a parameter to the Sort() method:
list.Sort(CompareObjects);
And C# will do the rest for you.