如何将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
相关产品推荐
相关产品推荐

