18

I have a object (product), with a property of type 'array'
e.g. product.tags = {"tag1","tag2","tag9"}

I have an array of input tags to filter on.

... but this is not quite working:

List<string> filterTags = new List<string>() { "tag1", "tag3" };

var matches = from p in products
  where p.Tags.Contains(filterTags)
  select p;

Any recommendations? Thanks.

2 Answers 2

45

What is the Contains really meant to achieve? Do all items in Tags need to exist in filterTags? Or at least one of them? For the latter use Any and for the former use All. Your where line would change to:

where p.Tags.Any(tag => filterTags.Contains(tag))

or

where p.Tags.All(tag => filterTags.Contains(tag))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks ... great. It meant 'any' actually. .... "... show all products that contain one-or-more of the input tags". I'll give that a go. THANK-YOU!
As LINQ for anyone interested: context.Products.Where(p => p.Tags.Any(tag => filterTags.Contains(tag)))
@Mike As LINQ? Isn't what's given in the answer LINQ? Of course it is. What you've shown is called extension method syntax BTW.
-1
var small = new List<int> { 1, 2 };
var big = new List<int> { 1, 2, 3, 4 };

bool smallIsInBig = small.All(x => big.Contains(x));
// true

bool bigIsInSmall = big.All(x => small.Contains(x));
// false

bool anyBigIsInSmall = big.Any(x => small.Contains(x));
// true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.