Let's say that I have the following list and method:
List<myObject> myList = (some function that prepopulates myList);
I would like to sort myList
in descending order using a method that I created:
int sortByThisValue(myObject obj)
{
int someInteger;
// Operations on obj that generates a value for someInteger
...
return someInteger;
}
The first solution that comes to mind is to create a sorted Dictionary and then extract the values as a list. However, this fails when two objects generate the same someInteger
because a dictionary must have a unique set of keys. What is the best way sort this list?
LINQ makes this easy:
// Method group conversion
List<myObject> sorted = myList.OrderByDescending(SortByThisValue).ToList();
// Lambda expression
List<myObject> sorted = myList.OrderByDescending(x => SortByThisValue(x))
.ToList();
Note that this does not sort the list in-place; it creates a new list. If you don't need to actually create a new list, just remove the ToList
call at the end, e.g.
foreach (MyObject item in myList.OrderByDescending(x => SortByThisValue(x))
{
// Do something
}
It's well worth looking into LINQ - it makes all kinds of data querying really simple.
If you absolutely need to sort in-place, you could use:
myList.Sort((x, y) => SortByThisValue(y).CompareTo(SortByThisValue(x)));
(Note the use of y
followed by x
here - that's what's reversing the "natural" ordering so that you get the values in descending order.)
It's uglier than the LINQ version though, IMO.
See more on this question at Stackoverflow