Reputation: 886
If I have the query below :-
var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
group data by new
{
InvNo = data.Field<double>("InvoiceNo"),
AccRef = data.Field<double>("SiteRefNum"),
}
into g
select new
{
Code = "1",
InvType = "I",
Account = g.Key.AccRef,
InvNo = g.Key.InvNo,
ChargeTotal = g.Sum(d => d.field<double>("Charge")
};
...what is the best method of excluding rows where the sum of column ChargeTotal is zero? I'm assuming I have to use a WHERE
, but I'm not sure where to place it.
Upvotes: 1
Views: 111
Reputation: 13022
You don't have many solutions because the where
must be called after the group by
(it depends on the groups), then:
var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
group data by new
{
InvNo = data.Field<double>("InvoiceNo"),
AccRef = data.Field<double>("SiteRefNum"),
}
into g
let sum = g.Sum(d => d.field<double>("Charge")) // Sum only computed once
where sum != 0
select new
{
Code = "1",
InvType = "I",
Account = g.Key.AccRef,
InvNo = g.Key.InvNo,
ChargeTotal = sum
};
To slightly improve performances (you have to test both to see if there is any performance improvement because it highly depends on the data), if d.field("Charge") is always >= 0, you can do:
var Values = from data in DtSet.Tables["tblCosts"].AsEnumerable()
group data by new
{
InvNo = data.Field<double>("InvoiceNo"),
AccRef = data.Field<double>("SiteRefNum"),
}
into g
where g.Any(d => d.field<double>("Charge") != 0)
select new
{
Code = "1",
InvType = "I",
Account = g.Key.AccRef,
InvNo = g.Key.InvNo,
ChargeTotal = g.Sum(d => d.field<double>("Charge"))
};
Upvotes: 5