1

Are

var movies = from m in db.Movies
             select m;

movies = movies.Where(s => s.Title.Contains(searchString));

and

var movies = from m in db.Movies
             where String.Equals(m.Title,searchString)
             select m;

equivalent? And if so, why use one over the other? The syntax of the former seems more cryptic than the latter.

jayflo
  • 1,105
  • 1
  • 12
  • 21

3 Answers3

2

Behind the scenes, there's some translations going on.

For LINQ to SQL (and LINQ to Entities), the select keyword effectively ends a query. So, the second example has the filter as part of the SQL query, while the first one executes after the query.

There's a third way to do a LINQ query, called fluent syntax:

var movies = db.Movies.Where(s => s.Title.Contains(searchString));

If you look at the signature of Where, you'd find this:

IQueryable<T> Where(IQueryable<T> source, Expression<Func<T,bool>> predicate);

The key thing is the type of predicate: it's an expression of a (lambda) function, rather than merely a (lambda) function. This lets .Net dynamically convert the Expression object to SQL. For the query syntax, this parsing ends at select.

Christopher Stevenson
  • 2,843
  • 20
  • 25
0

query expressions are compiled to method syntax by compiler when you compile the code, whichever way you write code is a matter of preference, query expressions are preferred by developers from sql background.. :)

Sukhdevsinh Zala
  • 1,126
  • 2
  • 14
  • 19
0

You're right, the latter form is more readable but sometimes you need the expression methods, like when you want to get the Count of result, and of course you can mix these two.

Arin Ghazarian
  • 5,105
  • 3
  • 23
  • 21