Ian Boyd
Ian Boyd

Reputation: 256951

How am i allowed to pass a method to List.Sort()?

i am calling Sort on a List:

List<Stuff> list = new List<Stuff>();
list.Sort(StuffSortByName);

with the StuffSortByName declaration of:

private static int StuffSortByName(Stuff x, Stuff y)
{
    ...
}

What surprises me is that my code compiles and works. It's surprising that no overload of Sort takes a method:

So i was fortunate, as i didn't want to have to create a whole object, that implements IComparer, just to sort stuff. But for the life of me i don't understand while it compiles.


And now i want to duplicate that magic. i want to sort a ListView. But you don't sort a listivew, you give a listview an IComparer through it's ListViewItemSorter property:

listView1.ListViewItemSorter = [IComparer]

And, again, i don't want to write a whole object, i just want to pass a local method (and ideally a non-static one):

listView1.ListViewItemSorter = SortListView;


private static int SortListView(Object x, Object y)
{
    ....
}

Now of course this doesn't compile because it makes no sense. But then the earlier syntax shouldn't compile either - but it does.

So it gives me hope that i can have the same confusing syntax here.

How was i allowed to pass a method as a sort comparer in the first case, but not in the second case?

Upvotes: 1

Views: 833

Answers (2)

Platinum Azure
Platinum Azure

Reputation: 46203

To answer your first question, the reason the method name can be passed is because Comparison<T> is a delegate type, meaning it is a type representing a method signature. See MSDN for details.

In your case, you should either create an IComparer object or have your Stuff object implement IComparable or IComparable<T> (if possible).

Upvotes: 4

Tigran
Tigran

Reputation: 62276

I think you simply use this overload. which uses Comparison

From link:

If comparison is provided, the elements of the List(Of T) are sorted using the method represented by the delegate

EDIT

What about ListView, as you noticed too, it implements IComparer and not Comparison, so you can not just pass a delegate to it.

Upvotes: 0

Related Questions