You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:15:23