3

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?

4 Answers 4

7
myList.Sort((x,y) => x.BlocksCovered.CompareTo(y.BlocksCovered)
Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

1

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.

2 Comments

FWIW, LINQ is usually smart enough to take advantage of underlying types, e.g. Count() will use ICollection<T>'s count property. I don't know about Sort() though.
+1 I agree in general, but on lists of "normal" size this is not an issue so I personally shoot for readability, and that's where the LINQ syntax is clearly better. Also the overall Big O doesn't change - sorting is O(n*log n), traversal is O(n).
0

I'd use Linq, for example:

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

2 Comments

the OrderBy doesn't affect the orginal list, it creates another list
True, but why is that relevant? If you want to sort the list permanently, then save the results as a new list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.