N K
N K

Reputation: 307

How to write an if statement for "a list does not contain a string"?

The following IF statement checks if the ListexceptionCM contains the selected value of the dropdown list.

List<string> ExceptionCM = new List<string>;
if(exceptionsCM.Any(s => ddl_model.SelectedValue.Contains(s)) )
{
       //do something
}

List<string> ExceptionPM;
List<string> ExceptionDL;
List<string> ExceptionCL;

I would like to change the statement, so I can check if the the 4 list doesn't contains the selected value of dropdown. Could you help me ?

Upvotes: 2

Views: 4074

Answers (3)

cuongle
cuongle

Reputation: 75296

You can use All to ensure all items in 4 lists do not contain:

var exceptions = new List<List<string>>()
{
    ExceptionCM, 
    ExceptionPM, 
    ExceptionDL, 
    ExceptionCL
}

if (exceptions.SelectMany(ex => ex)
              .All(s => !ddl_model.SelectedValue.Contains(s)))
{
}

Edit: Any is not correct in this case because it determines whether any elements of a collection satisfy a condition.

Upvotes: 1

Freeman
Freeman

Reputation: 5801

List<string> ExceptionCM = new List<string>;
foreach(List<yourType> list in YourLists<List<YourType>>)
{
    if(exceptionsCM.Any(s => !list.Contains(s)) )
    {
       //do something
    }
{
List<string> ExceptionPM;
List<string> ExceptionDL;
List<string> ExceptionCL;

Just add the ! (not) operator before your ddl_model.SelectedValue.Contains(s) that returns a bool.

Upvotes: 1

Tigran
Tigran

Reputation: 62248

You can do like:

//combine all lists into a single IEnumerable<string>
IEnumerable<string> unionList = ExceptionCM.Union(ExceptionPM)
                                              .Union(ExceptionDL)
                                                  .Union(ExceptionCL);

//check against union list
if(unionList .Any(s => !ddl_model.SelectedValue.Contains(s)) )
{
   //do something
}

Something like this.

Upvotes: 2

Related Questions