根据元素对 C# 列表进行排序
我有如下 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<ClassInfo> ClassInfoList;
如何根据 BlocksCovered 对 ClassInfoList 进行排序?
I have the C# class as follows :
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;
}
}
And I have C# List of ClassInfo() as follows
List<ClassInfo> ClassInfoList;
How can I sort ClassInfoList based on BlocksCovered?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这将返回按
BlocksCovered
排序的List
:请注意,您应该真正将
BlocksCovered
设为属性,现在您拥有公共字段。This returns a
List<ClassInfo>
ordered byBlocksCovered
:Note that you should really make
BlocksCovered
a property, right now you have public fields.如果您有对
List
对象的引用,请使用List
提供的Sort()
方法,如下所示。如果您使用
OrderBy()
Linq 扩展方法,您的列表将被视为枚举器,这意味着它将被冗余地转换为List
、排序,然后作为枚举器返回,需要再次转换为List
。If you have a reference to the
List<T>
object, use theSort()
method provided byList<T>
as follows.If you use the
OrderBy()
Linq extension method, your list will be treated as an enumerator, meaning it will be redundantly converted to aList<T>
, sorted and then returned as enumerator which needs to be converted to aList<T>
again.我会使用 Linq,例如:
I'd use Linq, for example: