1

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)));
Community
  • 1
  • 1
jason
  • 767
  • 2
  • 9
  • 24
  • What does ProductAttributes contain? In what cases does it not fetch the correct results? In general, it appears that All is the method you want, but not knowing more about your data, it's hard to help further. – Jim Wooley Oct 25 '11 at 17:45

1 Answers1

3

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.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • 1
    I appreciate the effort in this answer. It is returning exactly what i would expect. I was headed down a route of attempting to use intersect, but I think this solution is a bit clearer as to what is going on. I apologize for the strange var names, it was quick linqpad code that i pasted, however in gg actually has meaning to me. ;) – jason Oct 26 '11 at 22:32