我在知道如何在XML文件中对同一属性的多个实例求和时遇到问题。我的第一个想法是构建一个数组来保存值然后将它们加在一起。不幸的是,我的c#代码知识不在应有的位置。
double customerRate = Convert.ToDouble(
import.Elements("PriceSheets")
.Elements("PriceSheet")
.Where(priceSheet => priceSheet.Attribute("type").Value == "Cost"
&& priceSheet.Attribute("isAllocated").Value == "true"
&& priceSheet.Attribute("isSelected").Value == "true")
.First()
.Element("Total"));
下面是我读取的XML文件,其中包含重复属性Total
<Enterprises>
<PriceSheets>
<PriceSheet type="Cost"
chargeModel="NORMALIZED_MANUAL" isSelected="true" isAllocated="true"
currencyCode="USD" createDate="05/25/2017 15:03"
updateDate="05/25/2017 15:18" internalId="5099262823">
<AccessorialTotal>222.80</AccessorialTotal>
<SubTotal>780.69</SubTotal>
<Total>1003.49</Total>
</PriceSheet>
</PriceSheets>
</Enterprises>
答案 0 :(得分:1)
易于;你有大部分是正确的:
var sum =
import
.Elements("Enterprises")
.Elements("PriceSheets")
.Elements("PriceSheet")
.Where(priceSheet => priceSheet.Attribute("type").Value == "Cost"
&& priceSheet.Attribute("isAllocated").Value == "true"
&& priceSheet.Attribute("isSelected").Value == "true")
// Now you're working with a sequence of all the allocated and selected "Cost" price
// sheets. You got this far.
// So just grab their "Total" elements...
.Elements("Total")
// And sum their values.
.Sum(total => Convert.ToDouble(total.Value));