I need to check whether an item doesn't exist in a list of items in C#, so I have this line:
if (!myList.Any(c => c.id == myID)))
Resharper is suggesting that I should change that to:
if (myList.All(c => c.id != myID)))
I can see that they are equivalent, but why is it suggesting the change? Is the first implementation slower for some reason?
All() determines whether all elements of a sequence satisfy a condition. Any() determines whether any element of a sequence satisfies the condition.
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
The Linq All Operator in C# is used to check whether all the elements of a data source satisfy a given condition or not. If all the elements satisfy the condition, then it returns true else return false. There is no overloaded version is available for the All method.
The readability of the expression is to me a personal opinion.
I would read this
if (!myList.Any(c => c.id == myID)))
as 'is my item not in the collection'. Where this
if (myList.All(c => c.id != myID)))
reads as 'are all items in the collection different than my item'.
If the 'question' I want to ask -through my linq query- is 'is my item not in the list', then the first query better suits the question that I want to ask. The !
in front of the first query is not a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With