[英]How to sort a List on C#?
當我嘗試使用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”,因為它不是委托類型
您在這里有 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.