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

如何使用LINQ筛选出指定的Class A列表?

解决LINQ筛选Class A列表的问题

首先得明确你的核心需求:你想要从List<A> myList中筛选出那些包含至少一个B对象且B.attribute1 == "test"的A实例,对吧?先说说你现有写法的问题:

  • 第一个写法:

    myList.SelectMany(o => o.attribute3.Where(p => p.attribute1 == "test")).ToList()
    

    SelectMany的作用是把嵌套的集合"平铺"展开,这里你会得到所有符合条件的B对象组成的List<B>,而不是你要的List<A>。

  • 第二个写法:

    myList.SelectMany(o => o.attribute3.Select(p => p.attribute1 == "test")).ToList()
    

    内层的Select返回的是一个个bool值(判断每个B是否满足条件),所以最终你得到的是一堆bool组成的List<bool>,完全偏离了目标。

正确的写法分两种情况:

情况1:只保留符合条件的A对象(A的attribute3保留原集合)

如果只需要筛选出存在符合条件的B的A,用Where结合Any即可:

var filteredAList = myList.Where(a => a.attribute3.Any(b => b.attribute1 == "test")).ToList();
  • Any(b => b.attribute1 == "test")会检查当前A的attribute3集合中是否存在至少一个满足条件的B,返回true/false;
  • Where则会保留所有返回true的A对象,最终得到你需要的List<A>。

情况2:保留符合条件的A对象,同时只保留其attribute3中符合条件的B

如果你不仅要筛选A,还要把A的attribute3也过滤成只包含符合条件的B,可以用Where加投影(Select):

var filteredAWithFilteredB = myList
    .Where(a => a.attribute3.Any(b => b.attribute1 == "test"))
    .Select(a => new A
    {
        attribute1 = a.attribute1,
        attribute2 = a.attribute2,
        attribute3 = a.attribute3.Where(b => b.attribute1 == "test").ToList()
    })
    .ToList();

这里先筛选出符合条件的A,然后创建新的A实例(或者如果允许修改原对象,也可以直接修改attribute3),把attribute3替换成过滤后的B集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:10:38