tags:

views:

265

answers:

7

Unfortunately the names of these methods make terrible search terms, and I've been unable to find a good resource that explains the difference between these methods--as in when to use each.

Thanks.

Edit:

The sort of query that I'm trying to fully understand is something like this:

context.Authors.Where(a => a.Books.Any(b => b.BookID == bookID)).ToList();

And thanks to all who've answered.

+9  A: 

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.)

Jon Skeet
@Jon Skeet - EXISTS - http://msdn.microsoft.com/en-us/library/bfed8bca.aspx
JonH
@JonH: Yes, as I posted, it's part of `List<T>` - not part of LINQ.
Jon Skeet
+4  A: 

Just so you can find it next time, here is how you search for the enumerable Linq extensions. The methods are static methods of Enumerable, thus Enumerable.Any, Enumerable.Where and Enumerable.Exists.

As the third returns no usable result, I found that you meant List.Exists, thus:

I also recommend hookedonlinq.com as this is has very comprehensive and clear guides, as well clear explanations of the behavior of Linq methods in relation to deferness and lazyness.

Dykam
Thanks for the links. I searched for "ienumerable<>.any()" , which was close, I guess, but useless.
PolishedTurd
A: 

Any() returns true if any of the elements in a collection meet your predicate's criteria.

Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.

Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.

Jimmy Hoffa
Not on IList - only `List<T>`
Jon Skeet
+1  A: 

Also see this previous question: http://stackoverflow.com/questions/879391/linq-any-vs-exists-whats-the-difference

Coding Gorilla
+1  A: 

Any - boolean function that returns true when any of object in list satisfies condition set in function parameters. For example:

List<string> strings = LoadList();
boolean hasNonEmptyObject = strings.Any(s=>string.IsNullOrEmpty(s));

Where - function that returns list with all objects in list that satisfy condition set in function parameters. For example:

IEnumerable<string> nonEmptyStrings = strings.Where(s=> !string.IsNullOrEmpty(s));

Exists - basically the same as any but it's not generic - it's defined in List class, while Any is defined on IEnumerable interface.

Ivan Ferić
Your second example won't compile, as Where returns `IEnumerable<T>`.
Jon Skeet
Yeah, thanks. Fixed it.
Ivan Ferić
+1  A: 

IEnumerable introduces quite a number of extensions to it which helps you to pass your own delegate and invoking the resultant from the IEnumerable back. Most of them are by nature of type Func

The Func takes an argument T and returns TResult.

In case of

Where - Func : So it takes IEnumerable of T and Returns a bool. The where will ultimately returns the IEnumerable of T's for which Func returns true.

So if you have 1,5,3,6,7 as IEnumerable and you write .where(r => r<5) it will return a new IEnumerable of 1,3.

Any - Func basically is similar in signature but returns true only when any of the criteria returns true for the IEnumerable. In our case, it will return true as there are few elements present with r<5.

Exists - Predicate on the other hand will return true only when any one of the predicate returns true. So in our case if you pass .Exists(r => 5) will return true as 5 is an element present in IEnumerable.

abhishek
+1  A: 

context.Authors.Where(a => a.Books.Any(b => b.BookID == bookID)).ToList();

a.Books is the list of books by that author. The property is automatically created by Linq-to-Sql, provided you have a foreign-key relationship set up.

So, a.Books.Any(b => b.BookID == bookID) translates to "Do any of the books by this author have an ID of bookID", which makes the complete expression "Who are the authors of the book with id bookID?"

That could also be written something like

  from a in context.Authors
  join b in context.Books on a.AuthorId equal b.AuthorID
  where b.BookID == bookID
  select a;

UPDATE: Any() as far as I know, only returns a bool. If essensial implementation is:

 public Any(this IEnumerable<T> coll, Func<T, bool> predicate)
 {
     foreach(T t in coll)
     {
         if (predicte(t))
            return true;
     }
     return false;
 }
James Curran
I think the part that is throwing me is how Any() returns a bool, which means I'm reading "yes, the author does have a book in their collection that has this BookID." Is their another overload of Any() that returns something different?
PolishedTurd
Yeah, this is why I'm confused. The way the Any() method is chained makes no sense to me. It doesn't return a book, but rather a bool. Man alive am I out to sea on this one. Maybe I just need another pot of coffee. Thanks for all the effort, btw.
PolishedTurd
I'm not seeing the problem. Any() returns a bool, Where() expects a bool. Everyone's happy!
James Curran
This dunce cap makes my head itch, and gets distracting sometimes. I'm sure I'll get it eventually.
PolishedTurd