繁体   English   中英

c#排序列表 <KeyValuePair<int, string> &gt;

[英]c# Sorting a List<KeyValuePair<int, string>>

在C#中,我想按List<KeyValuePair<int, string>>中每个字符串的长度对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#中的等价物是使用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);
    }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM