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);
精彩评论