0

Is it possible to change this Linq to XML statement into a compiled query ?

myxmlnodeList2 = From el In mynode.<attributwert> 
                 Where el.Attribute("AttributID") = sAttributID.ToLower And el.Attribute("Verwendung") = sVerwendung 
                 Select el

I used this method: Msdn

This works perfectly, if I only have 1 single Where condition. So, how can I create a compiled query with 2 Where conditions?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
d1chty
  • 3
  • 2

2 Answers2

1

This already is a compiled query.

Quote from the MSDN:

queries in LINQ to XML are statically compiled [...]. This feature is built in to LINQ to XML, so you do not have to perform extra steps to take advantage of it

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • oh didn't see that, thank you so there is no way to improve the performance by using static compiled queeries ? – d1chty Jul 02 '13 at 11:33
1

Why are you trying to compile the LINQ to XML query beyond what the compiler does? Are you running into perf issues due to a large XML structure? If so, consider looking into the XStreamingElement implementation instead.

Also, you might want to consider using .First or .FirstOrDefault instead of Where in your query to short circuit the query. In your query, you have to iterate over the entire graph. Using the First methods, you stop evaluating once you get to the first valid match. Of course, if you do want a collection then .Where is perfectly valid.

A third thing that has nothing to do with performance, but is entirely stylistic. You may want to consider using XML Literals for both the element and attribute rather than mixing the literals with the string parameters:

Dim myAttribute = sAttributID.ToLower()    ' Pull this out to only parse once
myxmlnodeList2 = From el In mynode.<attributwert> 
                 Where el@AttributID = myAttribute
                 And el@Verwendung = sVerwendung 
                 Select el
Jim Wooley
  • 10,169
  • 1
  • 25
  • 43
  • I may misunderstand your answer, but using `Where` doesn't necessarily iterate the whole collection. If you stop iterating after you pulled out the first item, you iterated just as far as you would have with `First` – Daniel Hilgarth Jul 03 '13 at 07:23
  • @DanielHilgarth True. The point here is if you don't use First, the entire document may be parsed. Since the OP named the item "...nodeList", a single document may not be what he wanted in which case, the First comment here may not apply. The other recommendations are still valid. – Jim Wooley Jul 03 '13 at 20:06