从List中获取所需的对象
假设我有一个类“Person”
……
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
并且假设我有一个列表“listOfPerson”
,其中包含15个人......
List<Person> listOfPerson = new List<Person>();
现在我试图从这个列表中获取对象人最大年龄......
仔细阅读我不仅仅需要最大年龄...... 但整个对象......所以我也可以访问最大年龄的人的名字......。
谢谢............
Suppose I have one class “Person”
………
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
and suppose I have list “listOfPerson”
which contain say 15 person…
List<Person> listOfPerson = new List<Person>();
Now I trying to get Object person form this List with Max Age…..
Read Carefully I an not just need Max Age……
but entire object….so I can also access the name of the person with max Age…….
Thanks………
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自评论
在这种情况下,找到最大年龄然后对其进行过滤是值得的。有多种方法,但
如果结果是列表而不是
IEnumerable
很重要,那么一种简单的方法是包含可选的ToList()
扩展。From comments
In this case, it's worth it to find the maximum age and then filter on it. There are various approaches, but a straightforward method is
Include the optional
ToList()
extension if it's important that the result be a list instead of anIEnumerable<Person>
.如果列表很短,那么订购和选择第一个(如前所述)可能是最简单的。
如果您有一个较长的列表并且排序开始变慢(这可能不太可能),您可以编写自己的扩展方法来执行此操作(我使用 MaxItem 因为我认为 Max 会与现有的 LINQ 方法发生冲突,但我懒得去了解)。
或者,如果您需要退回所有最大物品:
If the list is short then ordering and selecting the first (as previously mentioned) is probably the easiest.
If you have a longer list and sorting it starts to get slow (which is probably unlikely), you could write your own extension method to do it (I used MaxItem because I think just Max would conflict with existing LINQ methods, but I'm too lazy to find out).
Or, if you need to return all the maximum items: