I have a class:
class Point
{
double X, Y;
}
From a List<Point>
, say I want the Point
where Point.X + Point.Y
is maximum in the list. How would I do this in LINQ?
This would be one way (though not optimal by any means):
List<Point> list = ...;
Point maxPoint = list.OrderByDescending(p => p.X + p.Y).First();
Another way which should perform much better, would involve modifying your Point
class to implement IComparable<T>
, like this:
class Point : IComparable<Point>
{
double X, Y;
public int CompareTo(Point other)
{
return (X + Y).CompareTo(other.X + other.Y);
}
}
... which would then allow you to simply do:
List<Point> list = ...;
Point maxPoint = list.Max();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With