user1438082
user1438082

Reputation: 2748

Check if value already is in list property

Below I am trying to see if the text is already contained in the list. The code always goes into the if statement.Why?

if(MyGlobals.ListOfItemsToControl.FindAll(x => x.sItemName == info.FullName ) != null)
{
   ...
}

Upvotes: 1

Views: 77

Answers (2)

ekad
ekad

Reputation: 14614

Use Enumerable.Any Method

if (MyGlobals.ListOfItemsToControl.Any(x => x.sItemName == info.FullName))
{
    ...
}

or List.Exists Method

if (MyGlobals.ListOfItemsToControl.Exists(x => x.sItemName == info.FullName))
{
    ...
}

Upvotes: 4

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

use Any instead of FindAll

if(MyGlobals.ListOfItemsToControl.Any(x => x.sItemName == info.FullName )) 

FindAll doesn't return null if value is not found, it returns an empty collection.

So you could do (but don't)

 if(MyGlobals.ListOfItemsToControl.FindAll(x => x.sItemName == info.FullName ).Any())

Upvotes: 7

Related Questions