gpt4 book ai didi

c# - LinqToXml 的优化

转载 作者:太空宇宙 更新时间:2023-11-03 12:38:42 26 4
gpt4 key购买 nike

谁能告诉我这是否正确,或者是否有更快/更清洁的方法?

//I load p as a xDoc so I can use linq to xml
XDocument myDoc = XDocument.Parse(p);
// retrieve each "Item" node except if orderedQuantity is 0 or name is "nullorderitem"
IEnumerable<XElement> orderedRes = from item in myDoc.Descendants("Item")
where ((double)item.Element("orderedQuantity") > 0 && item.Element("ResourceId").Name != "NULLOrderItem")
select item;

foreach (XElement xelem in orderedRes)
{
if(xelem.Element("Name").Value.ToLower() == "oneofmyvalueIneed"
|| xelem.Element("Name").Value.ToLower() == "anotherone"
|| xelem.Element("Name").Value.ToLower() == "yetanother")
{
FieldProperties elem = new FieldProperties();
elem.Fieldname = xelem.Element("Name").Value;
elem.Fieldvalue = xelem.Element("OrderedQuantity").Value;
lElem.Add(elem);
}
}

知道 lElem 是一个 FieldProperties 列表,而 FieldProperties 是一个看起来像这样的类:

FieldProperties
string fieldname
string fieldvalue

而p是一个看起来像的字符串

<items>
<item>
<resourceid>blablabla</resourceid>
<somerandomtag>whocares</somerandomtag>
<orderedquantity>0.0</orderedquantity>
</item>
<item>
<resourceid>oneofmyvalueIneed</resourceid>
<somerandomtag>whocares</somerandomtag>
<orderedquantity>1.0</orderedquantity>
</item>
<item>
<resourceid>yetanother</resourceid>
<somerandomtag>whocares</somerandomtag>
<orderedquantity>0.0</orderedquantity>
</item>
</items>

最佳答案

您可以使用 .Contains 方法改进 if 语句。

var validNames = new List<string> {"oneofmyvalueIneed","anotherone","yetanother"}

XDocument myDoc = XDocument.Parse(p);
var result = from item in myDoc.Descendants("Item")
where ((double)item.Element("orderedQuantity") > 0 &&
item.Element("ResourceId").Name != "NULLOrderItem") && // See Charles's comment about this line
validNames.Contains(iten.Element("Name").Value.ToLower())
select item;

foreach (var item in orderedRes)
{
FieldProperties elem = new FieldProperties();
elem.Fieldname = xelem.Element("Name").Value;
elem.Fieldvalue = xelem.Element("OrderedQuantity").Value;
lElem.Add(elem);
}

然后你也可以把foreach替换成

select new FieldProperties
{
Fieldname = item.Element("Name").Value,
Fieldvalue = xelem.Element("OrderedQuantity").Value
};

将它们全部加在一起+在访问子元素时进行一些优化:

var validNames = new List<string> {"oneofmyvalueIneed","anotherone","yetanother"}

XDocument myDoc = XDocument.Parse(p);
var result = from item in myDoc.Descendants("Item")
let value = item.Element("orderedQuantity")
let name = iten.Element("Name").Value.ToLower()
where ((double)value > 0 &&
item.Element("ResourceId").Name != "NULLOrderItem") && // See Charles's comment about this line
validNames.Contains(name)
select new FieldProperties
{
Fieldname = name
Fieldvalue = value
};

关于c# - LinqToXml 的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39914133/

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