如何用Linq从Person数组中获取年龄最大的Person对象列表?
如何用LINQ获取Person数组中年龄最大的对象列表?
问题背景
已定义Person类:
public class Person { public string name; public int age; //... }
同时有Person类型数组:
Person[] personArray;
现有实现
当前的实现是先按年龄降序排序,再提取所有年龄等于最大值的对象,但希望用一行代码完成:
public List<Person> GetBiggestAgeList(){ var sortedPeople = personArray.OrderByDescending(person => person.age).ToList(); int maxAge = sortedPeople[0].age; List<Person> answer = new List<Person>(); for(int i = 0; i < sortedPeople.Count; ++i){ if(sortedPeople[i].age == maxAge) answer.Add(sortedPeople[i]); else break; } return answer; }
一行代码实现方案
直接通过LINQ组合方法就能一行搞定:
public List<Person> GetBiggestAgeList() => personArray.Where(p => p.age == personArray.Max(p2 => p2.age)).ToList();
如果要处理数组为空的情况(原代码空数组会触发空引用异常),可以调整成带边界判断的版本:
public List<Person> GetBiggestAgeList() => personArray.Any() ? personArray.Where(p => p.age == personArray.Max(p2 => p2.age)).ToList() : new List<Person>();
补充说明
- 第一种写法逻辑简单直接:先拿到数组里的最大年龄,再筛选出所有年龄匹配的对象;
- 第二种写法加了空数组判断,避免空数组时报错,返回空列表更安全。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

