Doubt between Any and All in a lambda expression in a list

5

In a list, I have 12 records (hypothetical) and there is a field called ValorCampoFlag , where this field receives 1 or null , for example. If I do a validation on it and the result if there is at least one with a value of 1, should I use Any or All ?

minhaVarBool = minhaLista.All(l => l.ValorCampoFlag == 1);

Or so:

minhaVarBool = minhaLista.Any(l => l.ValorCampoFlag == 1);

What strategy should I use for this type of result, ie set a Boolean variable.

The list brings me several records and it is enough to have one in that condition to set the variable.

    
asked by anonymous 12.02.2015 / 13:30

1 answer

9

According to the documentation for Any and All if your description is correct you must use Any . It returns true if any of the elements satisfies the established condition.

  

Determines whether any element of a sequence satisfies a condition.

Any is "any", so if any element has this condition it will return a true . It will search to find an element that gives true , and it does not make sense to continue searching for all, so it can be very fast if you find it among the first elements.

All is "all", so if all elements have this condition it will return true . It has to evaluate all elements at all times.

    
12.02.2015 / 13:36