Felix J.
Felix J.

Reputation: 33

Loop a list and compare it's elements to a condition c#

I need to loop through a list. Each element should be compared to 2 conditions.

The problem is that for one element result can be True, for another False. I have to keep all these results and make the operation OR, in order to get the final result.

foreach (var elem in mappingList)
{
   if (elem._mappingStatus == enum_MappingStatus.E_MAPPING_OK 
     || elem._mappingStatus == enum_MappingStatus.E_MAPPING_OK_END)
    {
        statusConfiguration = true;
    }
    else
    {
        statusConfiguration = false;
    }
}

The problem that I don't know how to keep statusConfiguration for all elements and then compare them. If at leat one of the results is false then the final result should be also false.

Thanks in advance.

Upvotes: 1

Views: 546

Answers (2)

fubo
fubo

Reputation: 45947

Use Any() to determine if not any item with these conditions exists

If at leat one of the results is false then the final result should be also false

statusConfiguration = mappingList.Any(x => 
                      x._mappingStatus != enum_MappingStatus.E_MAPPING_OK &&       
                      x._mappingStatus != enum_MappingStatus.E_MAPPING_OK_END);

Upvotes: 6

xecollons
xecollons

Reputation: 608

You should break off the foreach after statusConfiguration has been 'falsed'.

bool statusConfiguration = true;
foreach (var elem in mappingList)
{
    if (elem._mappingStatus == enum_MappingStatus.E_MAPPING_OK 
    & elem._mappingStatus == enum_MappingStatus.E_MAPPING_OK_END)
    {
         statusConfiguration = true;
    }
    else
    {
        statusConfiguration = false;
        break;
    }
}
if (!statusConfiguration) {finalResult = false;}

Upvotes: 2

Related Questions