LINQ-SQL – Incorrect results from Count() from Lambda expressions
Check out the following C# code:
using (MyDataContext db = new MyDataContext()) { int count1 = db.MyTable.Count(t=> t.IsActive == true); int count2 = db.MyTable.Select(t => t.IsActive == true).Count(); }
Judging by you what you see above, both count1 and count2 should have the same value, no?
No!
If there are 10 records in MyTable, count2 will have be 10. If there are 5 records in the table that fit the IsActive == true lambda expression, than count2 will be 5.
Can anyone explain this?
At any rate, if you to use a Lamda expression to get a count, it’s a good idea to put the expression in the Count method itself, and not rely on a previous Select query to do it for you.
Incidentally, check out this query:
using (MyDataContext db = new MyDataContext()) { var q = from t in db.MyTable where t.IsActive == true select t.ID; int count3 = q.Count(); }
Guess what? The value for count3 is correct (as one would expect).
This is one of those cases where you just have to shake your head, do it the way that works, and move on.
More later – joel.