prosseek
prosseek

Reputation: 190749

Sorting C# List based on its element

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?

Upvotes: 3

Views: 5772

Answers (4)

Steve Guidi
Steve Guidi

Reputation: 20200

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.

Upvotes: 1

Carra
Carra

Reputation: 17964

myList.Sort((x,y) => x.BlocksCovered.CompareTo(y.BlocksCovered)

Upvotes: 7

neontapir
neontapir

Reputation: 4736

I'd use Linq, for example:

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

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160862

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.

Upvotes: 6

Related Questions