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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With