gpt4 book ai didi

c# - Linq to Xml,是否可以改进此查询?

转载 作者:数据小太阳 更新时间:2023-10-29 02:59:06 26 4
gpt4 key购买 nike

我正在尝试学习 LINQ to XML。我无法正确编写查询。我应该写什么来检索索引 MCCO 的代码列表?

<Indexes>
<Index Name="ARTP">
<Codes>
<Code>aaa</Code>
<Code>bbb</Code>
</Codes>
</Index>
<Index Name="MCCO">
<Codes>
<Code>ccc</Code>
<Code>ddd</Code>
</Codes>
</Index>
<Index Name="AWAY">
<Value>eee</Value>
</Index>
</Indexes>

我已经写了这篇文章,但我觉得有一种方法可以改进查询。我假设我的节点中有代码(而不是值)。

    private List<string> GetCodes(string name)
{
var indexes = from index in indexXmlDocument.Descendants("Index")
where index.Attribute("Name").Value == name
select new
{
Codes = index.Element("Codes").Elements("Code")
};
List<string> codes = new List<string>();
foreach (var code in indexes.Single().Codes)
{
codes.Add(code.Value);
}
return codes;
}

最佳答案

private IEnumerable<string> GetCodes(string name)
{
return indexXmlDocument.Descendants("Index")
.Where(e => e.Attribute("Name").Value == name)
.Descendants("Code")
.Select(e => e.Value);
}

关于c# - Linq to Xml,是否可以改进此查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5425662/

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