bool isEmployeeFound;
DbContext DatabaseContext = new DbContext(DatabaseConnectionString);
using (DatabaseContext )
{
isEmployeeFound= DatabaseContext .Persons.Any(p => p.ExternalId == "123"); -- 1st statement
isEmployeeFound= DatabaseContext .Persons.Count(p => p.ExternalId == "123") > 0; --2nd statement
}
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.
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?
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 Which method performs better: .Any() vs .Count() > 0? says Count() is optimized for Linq to objects and it performs better than Any.
I did explore some more and tried getting times using code snippet below
using (var _dbContext = new DbContext())
{
string caregiverId = "2301001";
string clientPhoneNumber = "9795397674";
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
bool iscareGiverFoundWithAny = _dbContext.Persons.Any(p => p.ExternalId == caregiverId);
bool isClientPhoneNumberFoundWithAny = _dbContext.PhoneNumbers.Any(ph => ph.Number == clientPhoneNumber);
var testResult1 = stopwatch.Elapsed;
stopwatch.Restart();
bool iscareGiverFoundWithCountExt = _dbContext.Persons.Count(p => p.ExternalId == caregiverId) > 0;
bool isClientPhoneNumberFoundWithCountExt = _dbContext.PhoneNumbers.Count(ph => ph.Number == clientPhoneNumber) > 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();
}
On running above code it shows Count is faster. I am confused.
Thoughts please?