【问题标题】:How to sort a List on C#?如何在 C# 上对列表进行排序?
【发布时间】:2021-06-24 15:54:47
【问题描述】:

当我尝试使用 LINQ 中的 Sort 方法时出现编译时错误消息。我的代码有什么问题?

提前致谢

public class tt
{
    public string zz;
    public string yy;
}

...   

var tts = new List<tt>();
var sorted = tts.Sort(x => x.yy); // <- Compile Time Error here

编译时错误:

无法将 lambda 表达式转换为类型“IComparer”,因为它不是委托类型

【问题讨论】:

  • .Sort(....) 是来自List&lt;T&gt; 的方法,而不是 LINQ 方法。
  • 您的意思是使用OrderBy() 而不是Sort()

标签: c# .net linq


【解决方案1】:

这里有 2 个选项。如果你想就地排序,即你希望tts本身被排序,使用Sort

   // Here we should explain how to compare two items (a and b)
   tts.Sort((a, b) => string.Compare(a.yy, b.yy));

如果您想分隔 sorted 列表(同时保留初始tts 完整),请输入OrderBy

   using System.Linq;

   ...

   // Here while given item x we should provide value to sort by (x.yy)
   var sorted = tts.OrderBy(x => x.yy).ToList(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 2018-07-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多