Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the element of a list which fulfills a certain condition

Tags:

c#

linq

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?

like image 431
John Tan Avatar asked Jul 14 '15 01:07

John Tan


1 Answers

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();
like image 92
sstan Avatar answered Nov 15 '22 04:11

sstan