您能提高这种 linq-to-xml 方法的性能吗?
今天早上我真的需要去别的地方。因此,我决定在这里发布一个性能问题。
下面的代码有效,但它多次调用 Load 和 Save 方法。这似乎远没有效率。请有人提供到目前为止加载和保存行发生在循环之外的代码。我只想调用一次加载和保存。
谢谢各位:)
public void RemoveNodes(IList<String> removeItems)
{
foreach (String removeItem in removeItems)
{
XDocument document = XDocument.Load(fullFilePath);
var results = from item in document.Descendants(elementName)
let attr = item.Attribute(attributeName)
where attr != null && attr.Value == removeItem.ToString()
select item;
results.ToList().ForEach(item => item.Remove());
document.Save(fullFilePath);
}
}
I really need to be somewhere else this morning. So, I have decided to post a performance question here instead.
The code below works but it calls Load and Save method multiple times. This seems far from efficient. Please could someone provide the code so far the load and save lines occur outside the loop. I wish to call load and save only once.
Thanks chaps :)
public void RemoveNodes(IList<String> removeItems)
{
foreach (String removeItem in removeItems)
{
XDocument document = XDocument.Load(fullFilePath);
var results = from item in document.Descendants(elementName)
let attr = item.Attribute(attributeName)
where attr != null && attr.Value == removeItem.ToString()
select item;
results.ToList().ForEach(item => item.Remove());
document.Save(fullFilePath);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您自己已经给出了答案 - 只需将
Load
和Save
调用移到循环之外即可。我不清楚您自己在实现这一点时遇到了问题...不过您也可以使您的查询稍微简单一些:
这使用了从
XAttribute
到string
的转换这一事实> 如果属性引用本身为 null,则返回 null。您甚至不需要使用查询表达式:
You've already given the answer yourself - just move the
Load
andSave
calls outside the loop. It's not clear to me where you were having problems implementing that yourself...You can make your query slightly simpler too though:
This uses the fact that the conversion from
XAttribute
tostring
returns null if the attribute reference itself is null.You don't even need to use a query expression: