LinQ嵌套集合查询 [英] LinQ nested collection query
问题描述
我是Linq的新手,无法解决以下问题.试图在互联网上检查很多,但没有得到正确的答案.
I am new to Linq and cannot resolve following problem. Tried checking a lot on internet but did not get proper answer.
我有以下查询:
var packages = from p in Packages
from cl in p.Categories
from temp in Clusters
where (cl.Id == temp.Key)
select p;
Categories是包含ID和名称的对象的集合.这里的簇是键和值对的字典.执行此查询时出现以下错误:
Categories is a collection of objects containing id and name. Clusters here is a dictionary of key and value pairs. I get following error when executing this query:
无法创建类型为'System.Collections.Generic.KeyValuePair`2'的常量值. 在这种情况下,仅支持基本类型(例如Int32,String和Guid).
Unable to create a constant value of type 'System.Collections.Generic.KeyValuePair`2'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
另一个选择是也为包中的每个类别的每个循环添加一个.有没有更清洁的方法可以做到这一点?
The other option is to add a for each loop for each category in package as well. Is there a cleaner way to do this?
推荐答案
var packages = Packages.Where(
p => p.Categories.Any(
c => Clusters.ContainsKey(c.Id)));
如果您只希望每个包一次出现在结果中. 由于您的问题中的ContainsKey为O(1)而不是O(Clusters.Count),因此效率更高.
If you want each package just once in the result. It is also more efficient, since ContainsKey is O(1) instead of O(Clusters.Count) in your question.
这篇关于LinQ嵌套集合查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!