Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ .Any VS .Exists - What's the difference?

Using LINQ on collections, what is the difference between the following lines of code?

if(!coll.Any(i => i.Value)) 

and

if(!coll.Exists(i => i.Value)) 

Update 1

When I disassemble .Exists it looks like there is no code.

Update 2

Anyone know why there is no code there for this one?

like image 584
Anthony D Avatar asked May 18 '09 19:05

Anthony D


People also ask

What is difference between System LINQ and System data LINQ?

To my understanding, System. Linq is generic-level implementation which relies on IEnumerable whereas System. Data. Linq is provider-specific (LINQ to SQL) which relies on IQueryable.

What is .ANY in C#?

The C# Linq Any Operator is used to check whether at least one of the elements of a data source satisfies a given condition or not. If any of the elements satisfy the given condition, then it returns true else return false. It is also used to check whether a collection contains some data or not.

What is better than LINQ?

The Best Option Is To Use IndexOf method of Array Class. Since it is specialized for arrays it will b significantly faster than both Linq and For Loop.

What is LINQ Why should we use LINQ and what are the benefits of using LINQ?

LINQ offers the following advantages: LINQ offers a common syntax for querying any type of data sources. Secondly, it binds the gap between relational and object-oriented approachs. LINQ expedites development time by catching errors at compile time and includes IntelliSense & Debugging support.


2 Answers

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.

like image 117
Meinersbur Avatar answered Sep 17 '22 16:09

Meinersbur


The difference is that Any is an extension method for any IEnumerable<T> defined on System.Linq.Enumerable. It can be used on any IEnumerable<T> instance.

Exists does not appear to be an extension method. My guess is that coll is of type List<T>. If so Exists is an instance method which functions very similar to Any.

In short, the methods are essentially the same. One is more general than the other.

  • Any also has an overload which takes no parameters and simply looks for any item in the enumerable.
  • Exists has no such overload.
like image 31
JaredPar Avatar answered Sep 16 '22 16:09

JaredPar