Reputation: 2748
I have 2 lists - I need to see if a value in one list property exists in a list property of a second list.I tried the code below but it does not compile. "Cannot implicitly convert type 'string' to 'bool'" - I think i should be using 'contains' but im not 100%
if(MyGlobals.ListOfItemsToControl.Any(x => x.sItemName == MyGlobals.lstNewItems.Any(y => y.sItemName)))
{
...
}
Upvotes: 1
Views: 266
Reputation: 13972
Why not use Intersect
?
if(MyGlobals.ListOfItemsToControl.Select(x => x.sItemName)
.Intersect(MyGlobals.lstNewItems.Select(y => y.sItemName)).Any())
{
// ...
}
You can also supply an IEqualityComparer
to perform whatever comparison between your objects which would probably make this code neater - especially if there is more than a simple string comparison.
Upvotes: 1
Reputation: 6366
if(MyGlobals.ListOfItemsToControl.Any
(x => MyGlobals.lstNewItems.Any(y => y.sItemName == x.sItemName)))
{
...
}
Upvotes: 9
Reputation: 149020
Another alternative
if(MyGlobals.ListOfItemsToControl.Join(
MyGlobals.lstNewItems,
x => x.sItemName,
y => y.sItemName,
(x, y) => x).Any())
{
...
}
Upvotes: 2