扩展方法和直接查询的区别
var selectedProducts = from p in products
where p.Category == 1
select p;
var selectedProducts = products.Where(p=>p.Category==1) ;
上述 2 个语句似乎产生相同的结果。
那么有什么区别(有时内部)?
哪一种效率更高?
var selectedProducts = from p in products
where p.Category == 1
select p;
var selectedProducts = products.Where(p=>p.Category==1) ;
The above 2 statements seems to produce same result.
Then what is the difference(some times internally)?
Which one is efficient more?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有什么区别。第一个(查询表达式)由编译器转换为第二个,并且对运行时间没有影响。
另请参阅:
There is no difference. The first (the query expression) is translated to the second by the compiler, and has no impact on run time.
See also:
在这种情况下,这两种方式没有任何区别,但在某些情况下最好使用查询,而在某些情况下最好使用扩展方法或不可能使用查询。
在像Join这样扩展方法复杂且不可读的情况下可以使用查询。
您还可以在某些情况下使用扩展方法,例如查询语法中不可用的 Distinct,您还可以使用扩展方法调用来使用
方法链接
以提高代码的可读性。您可以混合使用扩展方法和查询,但效果不好(代码可读性):例如
There isn't any difference between this two way in this case, but in some cases is better use query and In some cases is better to use extension method or impossible to use query.
you can use query in situation which are complicated with extension methods and unreadable like Join.
Also you can use extension method in some cases like Distinct which is not available in query syntax, Also you can use extension method calls for using
method chaining
to improve your code readability.You can use mix of extension method and query but is not good (code readability): like