Returns a list item that satisfies a specific condition.

I have a class:

class Point { double X, Y; } 

From a List<Point> , let's say I want Point , where Point.X + Point.Y is the maximum on the list. How to do it in LINQ?

+5
source share
4 answers

This will be one of the ways (although not optimal):

 List<Point> list = ...; Point maxPoint = list.OrderByDescending(p => pX + pY).First(); 

Another way that should work much better would be to modify your Point class to implement IComparable<T> , for example:

 class Point : IComparable<Point> { double X, Y; public int CompareTo(Point other) { return (X + Y).CompareTo(other.X + other.Y); } } 

... which then allows you to simply:

 List<Point> list = ...; Point maxPoint = list.Max(); 
+6
source

I would add Microsoft Reactive Team interactive extensions (NuGet "Ix-Main"). They have a bunch of very useful IEnumerable<T> extensions.

This is the one you need:

 Point max = points.MaxBy(p => pX + pY).First(); 
+2
source
 var maxValue = list.Max(m => mX + mY); var maxPoint = list.Where(p => pX + pY == maxValue).FirstOrDefault(); 

for the highlander ..

or

 var largestPoints = list.Where(p => pX + pY == maxValue); 

for connections.

0
source

There is nothing worth it. You can do:

 Point theMax = null; ForEach(x => theMax = (theMax == null || xX + xY > theMax.X + theMax.Y ? x : theMax)); 

But obviously this is not very pretty.

What you really need is to write your own extension method, and by writing your own I mean shamelessly stealing MoreLinq ( https://code.google.com/p/morelinq/source/browse/MoreLinq/MaxBy. cs ). You can also use: Install-Package MoreLinq.Source.MoreEnumerable.MaxBy

Then you can simply do: var theMax = points.MaxBy(x => xX + xY);

Remember that the beauty / power of Linq is such that at the end of the day, all extension methods. Do not forget that you can always write your own to do what you need. Of course, the MoreLinq project usually has what you need. This is a great library.

0
source

All Articles