choopau
choopau

Reputation: 2377

Which is better checking of null types or using Any() in LINQ?

I have this two codes and I have to know which is much better to use. I'm thinking this is the same. If I'm not mistaken, the first has only one call to the database, however, I don't know if checking of the repo != null is right.

(1)

var repo = Repository
  .Query()
  .Where(ur => ur.CustomerId == customerId)
  .SingleOrDefault();

if (repo != null)
{
    // Update repo
    repo.Name = "name here";
}
else
{
    // code
}

(2)

var repo = Repository
  .Query()
  .Any(ur => ur.CustomerId == customerId);

if (repo)
{
    var result = Repository
      .Query()
      .Where(ur => ur.CustomerId == customerId)
      .Single();

    result.Name = "name here";
}
else
{
    // code
}

Upvotes: 0

Views: 78

Answers (2)

user2216
user2216

Reputation: 839

The second option finds one element two times. Here

Repository
  .Query()
  .Any(ur => ur.CustomerId == customerId)

And here

Repository
  .Query()
  .Where(ur => ur.CustomerId == customerId)
  .Single()

And the first option finds just one time. It is a reason for choosing the first option. And also, you can make this code better:

var repo = Repository
  .Query()
  .Where(ur => ur.CustomerId == customerId)
  .SingleOrDefault();

Just write

var repo = Repository
  .Query()
  .SingleOrDefault(ur => ur.CustomerId == customerId);

And advice for future: use Any() when you want to check the fact that you has any element in query, but you don't need this element.

Upvotes: 6

mehrdad safa
mehrdad safa

Reputation: 1071

in the second approach you are navigating through items first by Any item to find a match, and again for getting match item. the SingleOrDefault wwill do the task in 1 step and checking one item (to determent if its null or not) is very cheaper than navigating all items.
so first approach is faster and better in my opinion.

Upvotes: 0

Related Questions