Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using linq to determine if any element is ListA exists in ListB?

Tags:

c#

list

linq

I'm trying to use PredicateBuilder to compose dynamic linq queries. In my object, I have a list of "Statuses" and I have another list of statuses that I want to search for.

So I need to be able to look in my object.Status property (a list) and see if it contains any of the items in my query list.

I've been fiddling around with .Any() and .Contains() but can't seem to find the right syntax.

What am I doing wrong? Below are some of the things I've tried, but none of them have the correct syntax.

myObject.Statuses.Contains(myStatusList);

myObject.Statuses.Any(myStatusList);

myObject.Statuses.Any(s => s == myStatusList);
like image 875
Amanda Kitson Avatar asked Jun 30 '11 15:06

Amanda Kitson


2 Answers

got.Any(x => want.Contains(x))

On further reflection, however, I'd write a ContainsAny extension method, to make this more readable. The implementation would probably be the same (although want.Intersect(got).Any() would also work).

like image 93
Roger Lipscombe Avatar answered Oct 18 '22 10:10

Roger Lipscombe


Do you mean:

myObject.Statuses.Any(s => myStatusList.Contains(s));

? This would be equivalent too:

myStatusList.Any(s => myObject.Statuses.Contains(s));
like image 37
Ry- Avatar answered Oct 18 '22 11:10

Ry-