c# 排序列表>.

本文关键字:string int KeyValuePair 排序 列表 | 更新日期: 2023-09-27 17:56:06

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

c# 排序列表<KeyValuePair<int, string>>.

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

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

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

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

您可以使用 linq 调用 OrderBy

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

有关@Guffa指出的内容的详细信息,请查找 Linq 和延迟执行,基本上它只会在需要时执行。因此,要立即从此行返回列表,您需要添加一个.ToList(),这将使要执行的表达式返回列表。

你可以使用它

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