0

I have written a LINQ Query to perform a simple where query against a database. However, I noticed there are two methods of doing this, the first I picked up from a book and the second is what I'm seeing mainly online:

First

    IQueryable<WebApi.Models.User>? users = db.Users?
        .Where(user => user.EmailAddress.Equals(loginRequest.EmailAddress) && user.Password.Equals(loginRequest.Password));

Second

    WebApi.Models.User user = (from u in db.Users
                where u.EmailAddress.Equals(loginRequest.EmailAddress) && u.Password.Equals(loginRequest.Password)
                select u).SingleOrDefault();

The first uses the IQueryable interface while the second does not. What is the difference between the two and does IQueryable provide any advantages over the local variable method?

Musaffar Patel
  • 905
  • 11
  • 26
  • BTW, for readability you can use `==` instead of `.Equals()`. – Dai Sep 09 '22 at 20:10
  • 1
    An `IQueryable` represents a (non-executed) query, not its results. Methods like `ToList`, `SingleOrDefault`, `Count`, etc will _materialize_ and actually execute the query. – Dai Sep 09 '22 at 20:11
  • Would it be reasonable to then assume that iQueryable is better for larger result sets? I am deciding which I should use throughout my project. – Musaffar Patel Sep 09 '22 at 20:14
  • 1
    Your two methods are not directly comparable. One returns multiple values, the other returns a single value. If in your first example you followed up with `WebApi.Models.User user = users.SingleOrDefault()` the two would be completely equivalent, and it wouldn't matter if you used an intermediate variable for the query or not. – D Stanley Sep 09 '22 at 20:19
  • @DStanley - Thanks, that's exactly what I needed to know, if they would be identical or not if they both return a single result. – Musaffar Patel Sep 09 '22 at 20:21
  • Yes they would - the second is actually using `IQueryable` too, you just don't see it because you've tacked on a `SingleOrDefault` to get a single result. – D Stanley Sep 09 '22 at 20:23
  • 2
    Musaffar, look up "query syntax" and "fluent syntax" for LINQ. I prefer fluent syntax. Check this out too https://stackoverflow.com/questions/214500/fluent-and-query-expression-is-there-any-benefits-of-one-over-other – Victor Wilson Sep 09 '22 at 20:24

0 Answers0