views:

6734

answers:

3

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 not code there for this one?

+31  A: 

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.

JaredPar
Well put (+1). List<T>.Exists has been around since .Net 2 but only works for generic lists. IEnumerable<T>.Any was added in .Net 3 as an extension that works on any enumerable collection. There's also similar members like List<T>.Count, which is a property and IEnumerable<T>.Count() - a method.
Keith
+1  A: 

Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.

flq
+18  A: 

See documentation

List.Exists (Object method)

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)

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.

Meinersbur