I have the next class and collection of this classes. How can I sort this collection by Perimeter() by asc?
public class Circle
{
private double _r;
public Double Radius
{
get { return _r; }
set { _r = value; }
}
public double Perimeter ()
{
return 2*Math.PI*Radius;
}
}
...
var lst = new List<Circle>();
lst = lst.OrderBy(x => x.Perimeter()).ToList()should to the trick. There is also anOrderByDescmethod available.Of course you can also use the LINQ query syntax as Rob4md propses, however keep in mind that all LINQ queries return an IEnumerable and are executed lazily.
You should use an eager operation like
ToList()orToArray()to execute them as soon as it makes sense because you may end up executing the enumeration multiple times.You may take a look at the 101 LINQ Samples page at the MSDN. There are many samples on how to use LINQ, OrderBy is covered, too.