Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 426
CodeKingPlusPlus Avatar asked Jan 27 '13 06:01

CodeKingPlusPlus


1 Answers

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();
like image 173
Guffa Avatar answered Sep 27 '22 22:09

Guffa