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

Anthony D picture Anthony D · May 18, 2009 · Viewed 331.8k times · Source

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?

Answer

Meinersbur picture Meinersbur · May 18, 2009

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.