gpt4 book ai didi

linq-to-xml - LINQ to XML GroupBy

转载 作者:行者123 更新时间:2023-12-04 17:12:52 25 4
gpt4 key购买 nike

我想使用 LINQ 通过在“摘要”字段上执行 GROUPBY 并将余额字段求和来将输入 XML 转换为输出 XML。

输入 XML:

<Root>
<Account>
<Summary>Checking</Summary>
<Comprehensive>Interest Checking Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>10000000.000000</Balance>
</Account>
<Account>
<Summary>Savings</Summary>
<Comprehensive>Market Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>20000000.000000</Balance>
</Account>
<Account>
<Summary>Checking</Summary>
<Comprehensive>Interest Checking Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>50000000.000000</Balance>
</Account>
</Root>

输出 XML:
<Root>
<Account>
<Summary>Checking</Summary>
<Comprehensive>Interest Checking Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>60000000.000000</Balance>
</Account>
<Account>
<Summary>Savings</Summary>
<Comprehensive>Market Account</Comprehensive>
<Currency>Dollar</Currency>
<Balance>20000000.000000</Balance>
</Account>
</Root>

我试过这个,但无法获得节点/元素:
XElement groupData = new XElement("Root",
chartData.Elements().GroupBy(x => x.Element("Summary").Value).
Select(g => new XElement("Account", g.Key, g.Elements("Comprehensive"),
g.Elements("Currency"),
g.Sum(
s =>
(decimal)
s.Element("Balance")))));

任何帮助,将不胜感激。提前致谢。

最佳答案

如果您不想要中间对象,您可以使用

    XDocument input = XDocument.Load("input.xml");
XDocument output =
new XDocument(
new XElement(input.Root.Name,
from account in input.Root.Elements("Account")
group account by account.Element("Summary").Value into g
select new XElement("Account",
g.ElementAt(0).Elements().Where(e => e.Name != "Balance"),
new XElement("Balance", g.Elements("Balance").Sum(b => (decimal)b)
))));
output.Save("output.xml");

或者你可以使用方法语法
    XDocument input = XDocument.Load(@"input.xml");
XDocument output = new XDocument(
new XElement(input.Root.Name,
input.Root.Elements("Account")
.GroupBy(a => a.Element("Summary").Value)
.Select(g => new XElement("Account",
g.ElementAt(0).Elements().Where(e => e.Name != "Balance"),
new XElement("Balance", g.Elements("Balance").Sum(b => (decimal)b)
)))));
output.Save("output.xml");

关于linq-to-xml - LINQ to XML GroupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5603284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com