tags:

views:

1167

answers:

6

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

+2  A: 

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.

Jeff Yates
+16  A: 

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.

cfeduke
A: 

Make sure if your ID property is the default value data type, such as Int or String. If the ID is an object reference type, that object should implement IComparer or IComparer.

David.Chu.ca
A: 

Sorry for previous post. The editor does not take < and > characters, and I did not notice the preview right under the editor. If the ID property is an object type, the object should implement IComparer or IComparer<T>.

David.Chu.ca
A: 

In future, if you want to debug problems like this, I'd advocate breaking out the delegate definition from the Sort call, like this:

Comparison<MyType> c = delegate(MyType t1, MyType t2){ ... };
myList.Sort(c);

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 =-)

Coderer
A: 

The way of obj.Sort(delegate(...)); is dynamic sorting in one place. If you have several places doing the same sorting or you need more flexible sorting, you may consider to create a class implementing IComparer<T>. Here is an example:

public class MyTypeComparer : IComparer<MyType>
{
  public MyTypeComparer() // default comparer on ID
  { ... }

  public MyTypeComparer(bool desc) // default with order specified

  public MyTypeComparer(string sort, bool desc) // specified sort and order such as property name, true or false.
  { ... }

  public int Compare(MyType a, MyType b) // implement IComparer interface
  { ... } // this is real sorting codes
}

and here is the example to use it:

List<MyType> myList = GetList();
myList.Sort(new MyTypeComparer());
// myList.Sort(new MyTypeComparer(false));
// myList.Sort(new MyTypeComparer("FirstName", true));
David.Chu.ca