LINQ .Any VS .Exists - What's the difference?
See documentation
List.Exists (Object method - MSDN)
Determines whether the List(T) contains elements that match the conditions defined by the specified predicate.
This exists since .NET 2.0, so before LINQ. Meant to be used with the Predicate delegate, but lambda expressions are backward compatible. Also, just List has this (not even IList)
IEnumerable.Any (Extension method - MSDN)
Determines whether any element of a sequence satisfies a condition.
This is new in .NET 3.5 and uses Func(TSource, bool) as argument, so this was intended to be used with lambda expressions and LINQ.
In behaviour, these are identical.
LINQ Any vs Exists Performance
Exists
requires an instance of List<T>
while Any
is invoked on IEnumerable<T>
. This means you have the potential for increased memory efficiency as IEnumerable<T>
can be evaluated lazily.
LINQ extension methods - Any() vs. Where() vs. Exists()
Where
returns a new sequence of items matching the predicate.
Any
returns a Boolean value; there's a version with a predicate (in which case it returns whether or not any items match) and a version without (in which case it returns whether the query-so-far contains any items).
I'm not sure about Exists
- it's not a LINQ standard query operator. If there's a version for the Entity Framework, perhaps it checks for existence based on a key - a sort of specialized form of Any
? (There's an Exists
method in List<T>
which is similar to Any(predicate)
but that predates LINQ.)
What is the difference between Contains and Any in LINQ?
Contains
takes an object, Any
takes a predicate.
You use Contains
like this:
listOFInts.Contains(1);
and Any
like this:
listOfInts.Any(i => i == 1);
listOfInts.Any(i => i % 2 == 0); // Check if any element is an Even Number
So if you want to check for a specific condition, use Any
. If you want to check for the existence of an element, use Contains
.
MSDN for Contains, Any
Linq Any() vs MoveNext()
Since IEnumerator<T>
implements IDisposable
(and thus can allocate resources) you have to put (in general case) not a simple line
// Don't do this: it can cause a resource leakage
HasChild = Childs.GetEnumerator().MoveNext() ? true : false;
but a fragment
bool HasChild = false;
using (var en = Childs.GetEnumerator()) {
HasChild = en.MoveNext(); // You have no need in ternary operator here
}
And it seems too wordy when in case of Any
all you should do
bool HasChild = Childs.Any();
And Enumerable<T>.Any
will do the wordy part for you:
http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,8788153112b7ffd0
public static bool Any<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
using (IEnumerator<TSource> e = source.GetEnumerator()) {
if (e.MoveNext()) return true;
}
return false;
}
What are the difference between .Select, .Any, and .Count when using LINQ
Count
needs to iterate the entire collection, because it (obviously) needs to count the number of instances.
Any
finds the first occurrence & returns true or false. If there aren't any, then it needs to iterate the whole collection to try to find, but if the first instance matches then it only needs to check the first instance.
Select
is completely different. It is used to project a collection into another collection. It does not perform any checking or filtering.
edit: In SQL terms, Any
is like Exists
, while Count
is like Count(*)
.
If I want to know whether there are any people on the street today, it is completely unnecessarily to count all the people and see if the number is >= 1. As soon as I find one person then I'm done.
Related Topics
How to Add Claims in ASP.NET Identity
How to Get the File Size in C#
What Is the Real Overhead of Try/Catch in C#
Best Way to Access Com Objects from C#
How to Sort an Observable Collection
Wpf Binding a Listbox to an Enum, Displaying the Description Attribute
Value Cannot Be Null. Parameter Name: Source
Best Way to Display Decimal Without Trailing Zeroes
How to Capture a 0..1 to 0..1 Relationship in Entity Framework
Difference with Parameters.Add and Parameters.Addwithvalue
Why Was "Switchto" Removed from Async Ctp/Release
How to Select Text from the Richtextbox and Then Color It
Linq .Any VS .Exists - What's the Difference
Pass Parameter to Eventhandler
Regex: I Want This and That and That... in Any Order