LinQ nested collection query

2019-08-31 14:13发布

问题:

I am new to Linq and cannot resolve following problem. Tried checking a lot on internet but did not get proper answer.

I have following query:

var packages = from p in Packages
               from cl in p.Categories
               from temp in Clusters
               where (cl.Id == temp.Key)
               select p;

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:

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?

回答1:

var packages = Packages.Where( 
                   p => p.Categories.Any( 
                   c => Clusters.ContainsKey(c.Id)));

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.



回答2:

Have you tried the query with the Dictionary.ContainsKey method?

var packages = from p in Packages
               from cl in p.Categories
               where Clusters.ContainsKey(cl.Id)
               select p;