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

C# 嵌套LINQ查询:如何筛选Attributes满足阈值的Person对象

解决方案

你可以直接使用LINQ的Any()方法实现嵌套集合的存在性校验,这是最简洁的实现方式,修改后的查询代码如下:

// 定义阈值
int threshold = 10;
// 嵌套LINQ查询,筛选同时满足年龄大于20、Attributes存在大于阈值元素的Person
var result = people.Where(p => p.Age > 20)
                   .Where(p => p.Attributes.Any(attr => attr > threshold))
                   .ToList();

说明

  • Any()是LINQ提供的标准查询运算符,专门用于判断序列中是否存在至少一个符合条件的元素,只要有一个元素满足条件就会立即返回true,不会遍历整个集合,性能表现优异。
  • 你也可以把两个过滤条件合并到同一个Where方法中,简化调用链:
var result = people.Where(p => p.Age > 20 && p.Attributes.Any(attr => attr > threshold)).ToList();
  • 如果你的业务场景中Attributes有可能为null,建议增加空值判断避免空引用异常:
// 写法1:显式判空
var result = people.Where(p => p.Age > 20 
                            && p.Attributes != null 
                            && p.Attributes.Any(attr => attr > threshold))
                   .ToList();
// 写法2:使用空条件运算符简化
var result = people.Where(p => p.Age > 20 
                            && p.Attributes?.Any(attr => attr > threshold) == true)
                   .ToList();

内容的提问来源于stack exchange,提问作者david

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:36:02