jason
jason

Reputation: 767

linq how to select a parent with a child collection that contains all of an array (or list) of values

similar to linq how to select a parent with a child collection that contains one or many of an array (or list) of values

How do you filter when the collection should contain all of the values in the array

var andAttributes = "super-quiet,electric-start".Split(',');

var andx = gg.Where(x => x.ProductAttributes.All(pa => andAttributes.Contains(pa.AttributeId)));

the above seems like it would work but doenst seem to.

For the given example, productAttributes is a generic list that may contain 1 or more specific values.

In english, i want to select only the objects that contain both the super-quiet AND electric-start values in the productAttributes collection.

This expression acts like an OR statement

var orx = gg.Where(x => x.ProductAttributes.Any(pa => orAttributes.Contains(pa.AttributeId)));

Upvotes: 1

Views: 3346

Answers (1)

Ani
Ani

Reputation: 113442

In english, i want to select only the objects that contain both the super-quiet AND electric-start values in the productAttributes collection.

Your existing query is filtering the objects for whom all its product attributes are contained in the test collection. But you appear to want to the reverse, i.e. filter the objects for whom all the attributes in the test-collection are contained in its product attributes.

var filteredGGs = from obj in gg                  
                  let objAttribIds = obj.ProductAttributes
                                        .Select(pa => pa.AttributeId)

                  where !andAttributes.Except(objAttribIds).Any()

                  select obj;

On another note, please try to name your variables better so that people are able to understand your intent better.

Upvotes: 3

Related Questions