简体   繁体   中英

What is the difference between these 2 XML LINQ Queries?

I have the 2 following LINQ queries and I haven't quite got my head around LINQ so what is the difference between the 2 approaches below?

Is there a circumstance where one approach is better than another?

ChequeDocument.Descendants("ERRORS").Where(x=>(string)x.Attribute("D") == "").Count();

    (from x in ChequeDocument.Descendants("ERRORS") where
                            (string)x.Attribute("D") == ""
                            select x).Count())

As Darin says, there's no difference. Personally I would prefer the first syntax, as all you've got is a single where clause in the query expresion. Note that the first syntax is more readable as:

var query = ChequeDocument.Descendants("ERRORS")
                          .Where(x=>(string)x.Attribute("D") == "")
                          .Count();

Also note that this is demonstrating a special case of query expressions. The second syntax is initially translated into:

var query = ChequeDocument.Descendants("ERRORS")
                          .Where(x=>(string)x.Attribute("D") == "")
                          .Select(x => x)
                          .Count();

but the compiler remove the no-op Select(x => x) . It doesn't do this in the case where there are no other clauses - so from x in y select x still becomes y.Select(x => x) .

There's no difference at all. The compiler converts the second syntax to the first one (look with Reflector at the compiled assembly) so it's really up to you to decide which syntax suits you best.

For me it the same. Only difference is that 1st is write with lambda expression, second with linq to xml.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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