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?
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
IComparerobject or have yourStuffobject implementIComparableorIComparable<T>(if possible).