Reputation: 190749
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
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
Reputation: 4736
I'd use Linq, for example:
ClassInfoList.OrderBy(c => c.ClassName);
Upvotes: 0
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