user1438082
user1438082

Reputation: 2748

Check if List value matches a list value in another list

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

Answers (3)

McAden
McAden

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

Paweł Bejger
Paweł Bejger

Reputation: 6366

if(MyGlobals.ListOfItemsToControl.Any
     (x => MyGlobals.lstNewItems.Any(y => y.sItemName == x.sItemName))) 
{
...
}

Upvotes: 9

p.s.w.g
p.s.w.g

Reputation: 149020

Another alternative

if(MyGlobals.ListOfItemsToControl.Join(
    MyGlobals.lstNewItems, 
    x => x.sItemName, 
    y => y.sItemName, 
    (x, y) => x).Any()) 
{
...
}

Upvotes: 2

Related Questions