LINQ: YOU TOO can count nothing n times!

by Grank March 18, 2008 12:16

One quick thing I've been meaning to blog about LINQ grouping and aggregation, that when you think about it makes sense but might not be immediately evident:
If you are doing a count aggregate on a field that implicitly joined to the key of a grouping join, you will get a count for all the rows, regardless of whether or not the field is NULL.

Consider the following LINQ snippet:

from l in Lawyers
join certInfo in
(
from a in Accounts
group a by a.Certificate into g
select new
{
Certificate = g.Key,
CommentCount = g.Key.CertificateComments.Count(),
TotalFees = g.Sum(a => a.TotalAmount),
TotalTariffs = g.Sum(a => a.TotalTariffAmount)
}
) on l equals certInfo.Certificate.Lawyer

This was a small part of a very large and complicated query we were trying to write in LINQ, and we were surprised to get a CommentCount of 4 rather than 1, the value we were expecting.  If you think about what has to be happening behind the scenes though, it's not that surprising.

The correction is simple:

from l in Lawyers
join certInfo in
(
from a in Accounts
group a by a.Certificate into g
select new
{
Certificate = g.Key,
CommentCount = g.Key.CertificateComments.Count(c => c != null),
TotalFees = g.Sum(a => a.TotalAmount),
TotalTariffs = g.Sum(a => a.TotalTariffAmount)
}
) on l equals certInfo.Certificate.Lawyer

Tags: , ,

Comments

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen | Modified by Mooglegiant

About The Author

I'm a software developer and musician in Edmonton, AB.  I write mostly web-based software, primarily on the Microsoft stack.  I have an MCPD and several MCTS, but I've only been at this whole developer thing for a few years, and the truth is that I'm still learning more than knowing.  So these are my adventures and experiments and some of it will probably be blatantly wrong...  Just warning ya.