LINQ to XML and LINQ to Objects

Why:

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

not as effective 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, this is the best operator that you can use to search for the element:

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

Thanks....

+4
source share
2 answers

If I am not mistaken, then from the point of view of high efficiency O is the same. This is 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(); 

may be easier expressed as

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

This should check every item in the listing.

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

This can stop testing the elements and return as soon as it finds something.

If you have a very large enumeration, and an element near the front satisfies the condition, then the first can be much faster. In the case when the number of elements satisfying the condition increases with the size of the enumeration, the acceleration can be asymptotic. For example, if one of every k elements satisfies the condition on average, then the average execution time of the second fragment is constant.

0
source

All Articles