I'm Attemping to do a SUM and a Group By in LINQ to XML. I'm also using LINQPad 4 to test my linq out. For some reason rate = g.Sum(taxRate) is giving me a FormatException error. I'm pretty sure this LINQ query could be cleared up as well. I know that "Taxrate" can be an empty string, I wish to just default 0 or ignore any empties. Any suggestions?
var tax = from taxRate in TaxRates.Descendants("Code")
where
taxRate.Attribute("taxrate") != null
&&
Int32.Parse(taxRate.Attribute("taxyear").Value) == TaxYear
group taxRate by taxRate.Attribute("taxunitid").Value into g
select new
{
ID = g.Key,
rate = g.Sum(taxRate => Decimal.Parse(taxRate.Attribute("taxrate").Value))
};
taxRatesByTaxUnit.Dump();
Here's some sample xml.
<Code taxyear="2005" tusfundid="12" cycleid="575" taxunitid="198674" taxrate=".214000000"/>
<Code taxyear="2005" tusfundid="13" cycleid="575" taxunitid="198674" taxrate=".004"/>
<Code taxyear="2005" tusfundid="13" cycleid="575" taxunitid="198674" taxrate=""/>
<Code taxyear="2005" tusfundid="13" cycleid="575" taxunitid="100000" taxrate=""/>
I expect to get back of
taxunit id: 198674: taxrate = .218
taxunit id: 100000: taxrate = .000
Okay, given the "tax rate of an empty string should be treated as 0", I would probably break that up into a separate method. It's simpler than trying to do it inline. Then I'd use explicit conversions everywhere.
So something like:
private decimal GetTaxRate(XElement code)
{
XAttribute rateAttribute = code.Attribute("taxRate");
return (string) rateAttribute == "" ? 0m : (decimal) rateAttribute;
}
...
var query = from code in TaxRates.Descendants("Code")
where (int?) code.Attribute("taxyear") == TaxYear
&& code.Attribute("taxRate") != null
group code by (string) code.Attribute("taxunitid") into g
select new {
ID = g.Key,
rate = g.Sum(code => GetTaxRate(code))
};
query.Dump();
See more on this question at Stackoverflow