Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem sorting lists using delegates

Tags:

I am trying to sort a list using delegates but I am getting a signature match error. The compiler says I cannot convert from an 'anonymous method'

List<MyType> myList = GetMyList();
myList.Sort( delegate (MyType t1, MyType t2) { return (t1.ID < t2.ID); } );

What am I missing?

Here are some references I found and they do it the same way.

Developer Fusion Reference

Microsoft Reference

like image 379
wusher Avatar asked Oct 23 '08 17:10

wusher


People also ask

How can I delegate queries/filters on a list?

That is going to take more work. In order for you to be able to delegate queries/filters on that list, you will need to do it by a delegable function and column type. You could use a number or text to do this.

What happens to the original three delegates when allmethodsdelegate is invoked?

The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method.

Is there a way to delegate a column in a list?

Calculated columns and "special columns" are not delegable either. The only real solution to create these "alternative" columns is through Flow/Workflow. OR, if your App is the ONLY consumer of the data in the list, then you can write the "alternate" column to the list at the time you create a new record.

Why do people put'C'at the end of delegate names?

That way, you can see if the problem is in your method call, or in your delegate definition. Some people prefer to leave it this way (with a more descriptive name than "c", obviously) to make the code more readable. I could take it or leave it =-)


2 Answers

I think you want:

myList.Sort( delegate (MyType t1, MyType t2) 
    { return (t1.ID.CompareTo(t2.ID)); } 
);

To sort you need something other than "true/false", you need to know if its equal to, greater than, or less than.

like image 190
cfeduke Avatar answered Oct 01 '22 03:10

cfeduke


The Sort doesn't take a binary predicate, it takes a Comparison<T> delegate which returns an int not a bool.

The return values are 0 for when the items are equal, <0 for when the first item is less than the second, and >0 for when the first item is greater than the second.

like image 28
Jeff Yates Avatar answered Oct 01 '22 01:10

Jeff Yates