19

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?
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216

3 Answers3

42

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();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
12

You can use linq calling OrderBy

list.OrderBy(o => o.Value.Length);

For more info on what @Guffa pointed out look for Linq and Deferred Execution, basically it will only execute when needed. So to immediately return a list from this line you need to add a .ToList() which will make the expression to be executed returning a list.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 3
    Note that the code doesn't actually do any work. You have to use `ToList` to actually do the sorting, and assign it back to the variable. – Guffa Jan 27 '13 at 06:20
4

u can use this

using System;
using System.Collections.Generic;

class Program
{
    static int Compare1(KeyValuePair<string, int> a, KeyValuePair<string, int> b)
    {
    return a.Key.CompareTo(b.Key);
    }

    static int Compare2(KeyValuePair<string, int> a, KeyValuePair<string, int> b)
    {
    return a.Value.CompareTo(b.Value);
    }

    static void Main()
    {
    var list = new List<KeyValuePair<string, int>>();
    list.Add(new KeyValuePair<string, int>("Perl", 7));
    list.Add(new KeyValuePair<string, int>("Net", 9));
    list.Add(new KeyValuePair<string, int>("Dot", 8));

    // Use Compare1 as comparison delegate.
    list.Sort(Compare1);

    foreach (var pair in list)
    {
        Console.WriteLine(pair);
    }
    Console.WriteLine();

    // Use Compare2 as comparison delegate.
    list.Sort(Compare2);

    foreach (var pair in list)
    {
        Console.WriteLine(pair);
    }
    }
}