简体   繁体   English

这两个XML LINQ查询之间有什么区别?

[英]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? 我有以下2个LINQ查询,但我还不太了解LINQ,所以下面的2种方法之间有什么区别?

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. 我个人更喜欢第一种语法,因为您所拥有的只是查询表达式中的单个where子句。 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) . 但是编译器删除了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) . 在没有其他子句的情况下不会执行此操作-因此from x in y select x仍然变为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. 编译器将第二种语法转换为第一种语法(在已编译的程序集上与Reflector一起查看),因此实际上由您决定哪种语法最适合您。

For me it the same. 对我来说也是一样。 Only difference is that 1st is write with lambda expression, second with linq to xml. 唯一的区别是,第一是使用lambda表达式编写,第二是使用linq to xml。

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

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