根据元素对 C# 列表进行排序

发布于 2024-10-20 21:23:08 字数 559 浏览 2 评论 0原文

我有如下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

℉絮湮 2024-10-27 21:23:08
myList.Sort((x,y) => x.BlocksCovered.CompareTo(y.BlocksCovered)
myList.Sort((x,y) => x.BlocksCovered.CompareTo(y.BlocksCovered)
扶醉桌前 2024-10-27 21:23:08

这将返回按 BlocksCovered 排序的 List

var results = ClassInfoList.OrderBy( x=>x.BlocksCovered).ToList();

请注意,您应该真正将 BlocksCovered 设为属性,现在您拥有公共字段。

This returns a List<ClassInfo> ordered by BlocksCovered:

var results = ClassInfoList.OrderBy( x=>x.BlocksCovered).ToList();

Note that you should really make BlocksCovered a property, right now you have public fields.

往日情怀 2024-10-27 21:23:08

如果您有对 List 对象的引用,请使用 List 提供的 Sort() 方法,如下所示。

ClassInfoList.Sort((x, y) => x.BlocksCovered.CompareTo(y.BlocksCovered));

如果您使用 OrderBy() Linq 扩展方法,您的列表将被视为枚举器,这意味着它将被冗余地转换为 List、排序,然后作为枚举器返回,需要再次转换为 List

If you have a reference to the List<T> object, use the Sort() method provided by List<T> as follows.

ClassInfoList.Sort((x, y) => x.BlocksCovered.CompareTo(y.BlocksCovered));

If you use the OrderBy() Linq extension method, your list will be treated as an enumerator, meaning it will be redundantly converted to a List<T>, sorted and then returned as enumerator which needs to be converted to a List<T> again.

合约呢 2024-10-27 21:23:08

我会使用 Linq,例如:

ClassInfoList.OrderBy(c => c.ClassName);

I'd use Linq, for example:

ClassInfoList.OrderBy(c => c.ClassName);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文