title: Any Vs Count in Entity Framework
body: <pre><code>bool isEmployeeFound;
  DbContext DatabaseContext = new DbContext(DatabaseConnectionString);
  using (DatabaseContext )
  {
      isEmployeeFound= DatabaseContext .Persons.Any(p =&gt; p.ExternalId == "123"); -- 1st statement
      isEmployeeFound= DatabaseContext .Persons.Count(p =&gt; p.ExternalId == "123") &gt; 0; --2nd statement
  }
  </code></pre>
  
  <p>My requirement is to check only If a given employee Id; exist in a table or not. I do not want the rows from table just a true or false. I am using Entity Framework not LINQ to Objects.</p>
  
  <p>I have been reading about Any and Count and kind of not able to decide; which one should I use? As shown above in my code should I use 1st or 2nd statement?</p>
  
  <p>I read that using Any(It converts to Exists in SQL) is faster because as soon it satisfied the condition it stops iterating and returns the result whereas Count()(It converts to select Count(*) in SQL) iterates all and then return the result. However this post <a href="https://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0">Which method performs better: .Any() vs .Count() &gt; 0?</a> 
  says Count() is optimized for Linq to objects and it performs better than 
  Any.</p>
  
  <p>I did explore some more and tried getting times using code snippet below</p>
  
  <pre><code>using (var _dbContext = new DbContext())
  {
      string caregiverId = "2301001";
      string clientPhoneNumber = "9795397674";
  
      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();
  
      bool iscareGiverFoundWithAny = _dbContext.Persons.Any(p =&gt; p.ExternalId == caregiverId);
      bool isClientPhoneNumberFoundWithAny = _dbContext.PhoneNumbers.Any(ph =&gt; ph.Number == clientPhoneNumber);
  
      var testResult1 = stopwatch.Elapsed;
      stopwatch.Restart();
  
      bool iscareGiverFoundWithCountExt = _dbContext.Persons.Count(p =&gt; p.ExternalId == caregiverId) &gt; 0;
      bool isClientPhoneNumberFoundWithCountExt = _dbContext.PhoneNumbers.Count(ph =&gt; ph.Number == clientPhoneNumber) &gt; 0;
  
      var testResult2 = stopwatch.Elapsed;
      stopwatch.Stop();
  
      Console.WriteLine("Any " + testResult2.TotalSeconds); -- value for this line is coming as 0.0276239
      Console.WriteLine("Count Ext. " + testResult3.TotalSeconds); -- value for this line is coming as 0.0054292
      Console.ReadLine();
  }
  </code></pre>
  
  <p>On running above code it shows Count is faster. I am confused.</p>
  
  <p>Thoughts please?</p>