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
( 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
{ Certificate = g.Key, CommentCount = g.Key.CertificateComments.Count(), TotalFees = g.Sum(a => a.TotalAmount), TotalTariffs = g.Sum(a => a.TotalTariffAmount) }
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
( 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
{ Certificate = g.Key, CommentCount = g.Key.CertificateComments.Count(c => c != null), TotalFees = g.Sum(a => a.TotalAmount), TotalTariffs = g.Sum(a => a.TotalTariffAmount) }
Tags: linq, group join, null
Related posts
Comments
Add comment
Powered by BlogEngine.NET 1.5.0.7 Theme by Mads Kristensen | Modified by Mooglegiant