Using Linq, order objects by some property and select first 2 objects

Using the linq query / method chainging method, I only want to select the first 2 Point objects in the list ordered by Point.X. How can I?

+2


source to share


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







All Articles