LINQ extension methods - Any() vs. Where() vs. Exists()

后端 未结 7 1727
清酒与你
清酒与你 2020-12-02 19:51

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

7条回答
  •  感情败类
    2020-12-02 20:26

    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. Its effective implementation is:

     public Any(this IEnumerable coll, Func predicate)
     {
         foreach(T t in coll)
         {
             if (predicte(t))
                return true;
         }
         return false;
     }
    

提交回复
热议问题