简体   繁体   English

使用Linq,按某些属性对对象进行排序,然后选择前2个对象

[英]Using Linq, order objects by some property and select the first 2 objects

Using a linq query/method chainging I wish to select just the first 2 Point objects in a List ordered by Point.X. 使用linq查询/方法chainging我希望只选择Point.X排序的List中的前2个Point对象。 How can I? 我怎样才能?

myList.OrderBy(item => item.X).Take(2);

Breaking it down: 打破它:

OrderBy() takes a lambda expression which selects the key by which to order. OrderBy()接受一个lambda表达式,该表达式选择要订购的密钥。 In this case, we want to return the .X property on the object. 在这种情况下,我们希望在对象上返回.X属性。 Another example is if we had a Person object and wanted to sort by .FirstName , the key selector would be (item => item.FirstName) . 另一个例子是如果我们有一个Person对象并希望按.FirstName排序,则键选择器将是(item => item.FirstName)

Take() truncates the enumeration to the specified number. Take()将枚举截断为指定的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM