-1

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.

paparazzo
  • 44,497
  • 23
  • 105
  • 176

1 Answers1

1

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.

Ismael Medeiros
  • 67
  • 1
  • 12
  • As I stated I know how to pass a Comparison to a Sort. I want to pass a comparison to an object (or object method) so the object can reference the comparison. – paparazzo Jun 03 '18 at 17:43
  • I think you can declare a delegate of your Class already specifying the paremeters' type `public delegate ComparisonDelegate(MyClass a, MyClass b);` as if there was some field of the method. After that you can declare some field, whose "type" is ComparisonDelegate. Or you can create a method Sort(ComparisonDelegate delegate) and pass this delegate to the Sort() method. A delegate can receive a method the same way Sort receives. – Ismael Medeiros Jun 03 '18 at 17:53
  • I do not want to use it for a sort. I am looking for object to object comparison. – paparazzo Jun 03 '18 at 18:04
  • Sorry, I was misunderstanding you. And how would be this comparison using the Comparisorison delegate, that you want? It would be the method CompareTo() from the IComparable method? Or inside other method? Or even overriding the operators (>, <, ==, <=, >=)? – Ismael Medeiros Jun 03 '18 at 18:13
  • Standard comparison that returns -1, 0, 1. I may have figured it out. I am going to post what I have. – paparazzo Jun 03 '18 at 18:26
  • The CompareTo() implements this. Liked you posted. – Ismael Medeiros Jun 03 '18 at 19:05
  • I was stuck on how to pass the delegate to the object. – paparazzo Jun 03 '18 at 19:07