c#对List进行排序<keyvaluepair <int,string =“”>&gt; </keyvaluepair <int,>

时间:2013-01-27 06:13:35

标签: c# list sorting compare keyvaluepair

在C#中,我想按列表中每个字符串的长度对List<KeyValuePair<int, string>>进行排序。在Psuedo-Java中,这将是一个匿名的,看起来像:

  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. 如何获得上述功能?

3 个答案:

答案 0 :(得分:29)

C#中的等价物是使用lambda表达式和Sort方法:

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

您还可以使用OrderBy扩展方法。它的代码略少,但它增加了更多的开销,因为它创建了列表的副本而不是将其排序到位:

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

答案 1 :(得分:10)

您可以使用linq调用OrderBy

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

有关@Guffa指出查找Linq and Deferred Execution的更多信息,基本上它只会在需要时执行。因此,要立即从此行返回一个列表,您需要添加一个.ToList(),这将使表达式返回一个列表。

答案 2 :(得分:3)

你可以用这个

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