简体   繁体   English

LINQ to XML和LINQ to Objects语法

[英]LINQ to XML and LINQ to Objects syntax

Why is: 为什么是:

(CheckBox)lstControls.Where(x => x.ID == "some_id").SingleOrDefault();

not as efficient as: 不如:

(CheckBox)lstControls.SingleOrDefault(x => x.ID == "some_id");

And for a not-so-well-formed XML document and you only know the name of the element you are looking for is this the best statement you can use to find the element: 对于格式不太完善的XML文档,您只知道要查找的元素的名称,这是可以用来查找元素的最佳语句:

var xmlElem = (from n in xDocument.Descendants() where (string)n.Attribute("name") == "some_node_name" select n).SingleOrDefault();

Thanks.... 谢谢....

If I'm not mistaken, in terms of big O efficiency, it's the same. 如果我没记错的话,就O效率而言,它是相同的。 It's just an extra method call. 这只是一个额外的方法调用。

Regarding the second question, 关于第二个问题,

var xmlElem = (from n in xDocument.Descendants() where (string)n.Attribute("name") == "some_node_name" select n).SingleOrDefault();

can be expressed more simply as 可以更简单地表示为

var xmlElem = xDocument.Descendants().SingleOrDefault(n => (string)n.Attribute("name") == "some_node_name");
(CheckBox)lstControls.Where(x => x.ID == "some_id").SingleOrDefault();

This must test every item in the enumeration. 这必须测试枚举中的每个项目。

(CheckBox)lstControls.SingleOrDefault(x => x.ID == "some_id");

This can stop testing items and return as soon as it finds something. 这样可以停止测试项目,并在发现问题后立即返回。

If you have a very large enumeration, and an item near the front satisfies the condition, then the former may be significantly faster. 如果枚举非常大,并且靠近前部的项目满足条件,则前者可能会快得多。 In the case where the number of items satisfying the condition increases with the size of the enumeration, the speedup may be asymptotic. 在满足条件的项目数随着枚举的大小而增加的情况下,加速可能是渐近的。 For instance, if one out of every k items on average satisfies the condition, then the average run time of the second snippet is constant. 例如,如果平均每k个项目中有一个满足条件,则第二个代码段的平均运行时间是恒定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM