In C# I would like to sort a List<KeyValuePair<int, string>> by the length of each string in the list. In Psuedo-Java this would be an anonymous and would look something like:
Collections.Sort(someList, new Comparator<KeyValuePair<int, string>>( {
public int compare(KeyValuePair<int, string> s1, KeyValuePair<int, string> s2)
{
return (s1.Value.Length > s2.Value.Length) ? 1 : 0; //specify my sorting criteria here
}
});
- How do I get the above functionality?
The equivalent in C# would be to use a lambda expression and the
Sortmethod:You can also use the
OrderByextension method. It’s slightly less code, but it adds more overhead as it creates a copy of the list instead of sorting it in place: