Using Linq find the first object in sorting the list by property A, then property B

I have an unordered list of Points ( List<Point>), and I want to find the first point in the list when sorting by X and then by Y.

NOTE. I do not want to reorder the items in the list.

+3
source share
2 answers

This will not change the order of the original list, but it will sort the resulting list enumeration and select the first point after the order. It handles an empty list case, returning the default value (null).

var firstPoint = Points.OrderBy( p => p.X ).ThenBy( p => p.Y ).FirstOrDefault();
+10
source
var firstPoint = (from p in Points orderby p.X, p.Y select p).FirstOrDefault();
+5
source

Source: https://habr.com/ru/post/1718431/


All Articles