简体   繁体   English

如何在 C# 上对列表进行排序?

[英]How to sort a List on C#?

I've an compile time error message when I try to use the Sort method from LINQ .当我尝试使用LINQ 中Sort方法时,出现编译时错误消息。 What's wrong with my code?我的代码有什么问题?

Thanks in advance提前致谢

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

Compile Time Error :编译时间错误:

Cannot convert lambda expression to type 'IComparer' because it is not a delegate type无法将 lambda 表达式转换为类型“IComparer”,因为它不是委托类型

You have 2 options here.您在这里有 2 个选择。 If you want to sort inplace , ie you want tts itself being sorted, use Sort :如果您想就地排序,即您希望tts本身被排序,请使用Sort

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

If you want to have separated sorted list (while initial tts being preserved intact ), put OrderBy :如果您想分离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(); 

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

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