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

Asked

Viewed 1,589 times

5

On 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 value 1, I should 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, i.e., set a boolean variable.

The list brings me several records and just have one in this condition to set the variable.

1 answer

9


According to the documentation of Any() and All() if your description is correct you should use the Any. She returns true whether any of the elements meets the condition.

Determines whether any element of a Quence satisfies a condition.

Any is "any", so if any element has this condition it will return a true, just one. He will search until he finds an element that gives true, and it doesn’t make sense to keep searching for everyone, so it can be very fast to find among the first elements.

All is "all", so if all elements have this condition will return true. He has to evaluate all the elements always.

  • The 'Any' option also has better performance, because when finding the first item in the list that meets the condition it for the enumeration process, while All always checks all items in the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.