Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am fetching data from the database using Entity Framework and Linq queries. I am wondering about the performance of getting data. I just want to check whether or not a well exists in the database. The database table has 15 columns and the number of rows are unknown.

internal static bool WellExists(string name, DatabaseContext context)
    var name = context.Wells.Where(w => == name).Select(w =>;
    return !string.IsNullOrEmpty(databaseUwi);

Here my point of concern is the line in which I am using Linq queries. In this I am using a Where, then Select and then FirstOrDefault. Another solution is using FirstOrDefault only.

var well = context.Wells.FirstOrDefault(w => == name);
return !(well == null);

The first query will get only selected data (Select) which is not required. Which solution's performance is better?

share|improve this question
I suggest perhaps profiling the query and seeing what the underlying SQL is. LinqPad is quite good for this, or I believe you should be able to see the SQL in debugger. In spite of that I think you will find all your examples generate the same underlying SQL – dreza May 9 '14 at 9:51
If you want to know the performance of something measure it and then you'll know. This question is like saying "I have a horse, does anyone know how fast it runs?" How should we know? If you have two horses and want to know which is faster, race them, don't ask strangers on the internet which one will win the race. – Eric Lippert May 9 '14 at 13:46
up vote 14 down vote accepted

You can try the .Any function on IQueryable. It is made for checking if there are any records.

Remember that .Any() has an overload that takes an expression, making the solution

internal static bool WellExists(string name, DatabaseContext context)
    return context.Wells.Any(x => x.Name == name);

I'm going to add a comment about your code as well. In the second example you have return !(well == null). This obfuscates the meaning of the code a bit, and would be clearer if you write return well != null;

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.