Question

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?
Was it helpful?

Solution

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();

OTHER TIPS

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.

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);
    }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top