Using linq to determine if any element is ListA exists in ListB?
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 s开发者_StackOverflow社区yntax.
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);
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).
Do you mean:
myObject.Statuses.Any(s => myStatusList.Contains(s));
? This would be equivalent too:
myStatusList.Any(s => myObject.Statuses.Contains(s));
What about intersect http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#intersect1
public void Linq50()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var commonNumbers = numbersA.Intersect(numbersB);
Console.WriteLine("Common numbers shared by both arrays:");
foreach (var n in commonNumbers)
{
Console.WriteLine(n);
}
}
精彩评论