Question

I have a list of Points. List<Point> points = new List<Point>();

I want to get the biggest value of y coordinates inside the list, given the condition that it only scans the coordinates inside the list with a specific x coordinate.

For example:

I have points like this

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
(2,1)
(2,2)
(2,3)
(2,4)
(2,5)

I want to find the biggest value of y-axis or y-coordinate, given that it only search coordinates with 2 as value of x. so the output must be (2,5)

Was it helpful?

Solution

Use LINQ to get point with biggest Y coordinate:

Point maximumPoint = points.First(p => p.X == 2 &&
                                       p.Y == points.Max(po => po.Y));

OR

Point maximumPoint = new Point(2, points.Where(p => p.X == 2).Max(p => p.Y));

OTHER TIPS

With LINQ, you can do:

var result = points.Where(point => point.X == 2)
                   .Max(point => point.Y);

If you want the Point instead of just the Y-coordinate, it's simple enough to just new up a Point wih (2, result). But in more complex cases, consider a MaxBy operator, such as the one that comes with morelinq.

With linq, this would by

var maxY = points.Where(p => p.X == 2).Select(p=> p.Y).Max();

This perhaps:

var maxY = points.Where(po => po.X == 2).Max(po => po.Y);
var q = points.Where(p => 
        p.Y == maxY  && 
        p.X == 2).FirstOrDefault();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top