开发者

Sorting C# List based on its element

开发者 https://www.devze.com 2023-02-15 04:40 出处:网络
I have the C# class as follows : public class ClassInfo { public string ClassName; public int BlocksCovered;

I have the C# class as follows :

public class ClassInfo {
    public string ClassName;
    public int BlocksCovered;
    public int BlocksNotCovered;


    public ClassInfo() {}

    public ClassIn开发者_如何学Gofo(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?


myList.Sort((x,y) => x.BlocksCovered.CompareTo(y.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.


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.


I'd use Linq, for example:

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

精彩评论

暂无评论...
验证码 换一张
取 消