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

如何将IQueryable<ICollection<ChildAccount>>转换为List<ChildAccount>?

解决IQueryable<ICollection>转List的问题

这个问题很常见,核心是你需要把嵌套的集合扁平化成单级序列,用SelectMany代替原来的Select就能搞定!

正确写法

var a = DBContext.Summaries
    .Where(fs => fs.PersonID == id)
    .SelectMany(s => s.ChildAccounts)
    .ToList();

为什么原来的写法不行?

你之前用Select的时候,会把每个Summary对应的ChildAccounts(ICollection<ChildAccount>)作为独立元素放入结果序列,所以最终得到的是IQueryable<ICollection<ChildAccount>>——相当于一个“集合的集合”。

而SelectMany的作用就是把这些嵌套的集合全部“展开”,将所有ChildAccount元素合并成一个连续的IQueryable<ChildAccount>序列,最后调用ToList()就能直接得到你需要的List<ChildAccount>。

可选:去重处理

如果不同Summary下可能存在重复的ChildAccount,可以在SelectMany之后添加Distinct()来过滤重复项:

var a = DBContext.Summaries
    .Where(fs => fs.PersonID == id)
    .SelectMany(s => s.ChildAccounts)
    .Distinct()
    .ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:56:11