c# Sorting a List<KeyValuePair<int, string>>

CodeKingPlusPlus picture CodeKingPlusPlus · Jan 27, 2013 · Viewed 40.9k times · Source

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
      }
    });
  1. How do I get the above functionality?

Answer

Guffa picture Guffa · Jan 27, 2013

The equivalent in C# would be to use a lambda expression and the Sort method:

someList.Sort((x, y) => x.Value.Length.CompareTo(y.Value.Length));

You can also use the OrderBy extension 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:

someList = someList.OrderBy(x => x.Value.Length).ToList();