Using Linq, order objects by some property and select first 2 objects
1 answer
myList.OrderBy(item => item.X).Take(2);
Destruction:
OrderBy()
takes a lambda expression that selects a key that can be ordered. In this case, we want to return a property .X
to an object. Another example: if we had an object Person
and wanted to sort by .FirstName
, the key selector would be (item => item.FirstName)
.
Take()
truncates the enumeration to the specified number.
+8
source to share