views:

50

answers:

3

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())
+2  A: 

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.

Darin Dimitrov
+3  A: 

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).

Jon Skeet
A: 

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

netmajor