Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Resharper suggest that I simplify "not any equal" to "all not equal"? [duplicate]

Tags:

c#

linq

resharper

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?

like image 804
Fiona - myaccessible.website Avatar asked Dec 20 '13 13:12

Fiona - myaccessible.website


People also ask

What is the difference between any and all in Linq?

All() determines whether all elements of a sequence satisfy a condition. Any() determines whether any element of a sequence satisfies the condition.

How use any LINQ query?

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.

What is all in Linq C#?

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.


1 Answers

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.

like image 71
Maarten Avatar answered Oct 24 '22 09:10

Maarten