[英]Sorting C# List based on its element
我有C#類如下:
public class ClassInfo {
public string ClassName;
public int BlocksCovered;
public int BlocksNotCovered;
public ClassInfo() {}
public ClassInfo(string ClassName, int BlocksCovered, int BlocksNotCovered)
{
this.ClassName = ClassName;
this.BlocksCovered = BlocksCovered;
this.BlocksNotCovered = BlocksNotCovered;
}
}
我有ClassInfo()的C#List如下
List<ClassInfo> ClassInfoList;
如何基於BlocksCovered對ClassInfoList進行排序?
這將返回一個List<ClassInfo>
通過有序BlocksCovered
:
var results = ClassInfoList.OrderBy( x=>x.BlocksCovered).ToList();
請注意,您應該將BlocksCovered
屬性,現在您擁有公共字段。
myList.Sort((x,y) => x.BlocksCovered.CompareTo(y.BlocksCovered)
如果您對List<T>
對象有引用,請使用List<T>
提供的Sort()
方法,如下所示。
ClassInfoList.Sort((x, y) => x.BlocksCovered.CompareTo(y.BlocksCovered));
如果您使用OrderBy()
Linq擴展方法,您的列表將被視為枚舉器,這意味着它將被冗余地轉換為List<T>
,排序然后作為枚舉器返回,需要轉換為List<T>
再次。
我使用Linq,例如:
ClassInfoList.OrderBy(c => c.ClassName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.