流利和查询表达-相对于其他有什么好处吗? [英] Fluent and Query Expression — Is there any benefit(s) of one over other?

查看:51
本文介绍了流利和查询表达-相对于其他有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LINQ是自.generic以来对.NET的最大改进之一,它为我节省了大量时间和代码行.但是,对我来说,流利的语法似乎比查询表达式语法更自然.

LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.

var title = entries.Where(e => e.Approved)
    .OrderBy(e => e.Rating).Select(e => e.Title)
    .FirstOrDefault();

var query = (from e in entries
             where e.Approved
             orderby e.Rating
             select e.Title).FirstOrDefault();

两者之间是否有区别?或者一个人相对于另一个人有什么特别的好处?

Is there any difference between the two or is there any particular benefit of one over other?

推荐答案

两者都不是更好:它们满足不同的需求.当您要利用多个范围变量时,查询语法就会发挥作用.在三种情况下会发生这种情况:

Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage multiple range variables. This happens in three situations:

  • 使用let关键字时
  • 当您有多个生成器时( from 子句)
  • 加入时
  • When using the let keyword
  • When you have multiple generators (from clauses)
  • When doing joins

这是一个示例(来自LINQPad示例):

Here's an example (from the LINQPad samples):

string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };

var query =
  from fullName in fullNames
  from name in fullName.Split()
  orderby fullName, name
  select name + " came from " + fullName;

现在将其与方法语法中的相同内容进行比较:

Now compare this to the same thing in method syntax:

var query = fullNames
  .SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
  .OrderBy (x => x.fName)
  .ThenBy  (x => x.name)
  .Select  (x => x.name + " came from " + x.fName);

另一方面,

方法语法可显示查询运算符的全部范围,并且对于简单查询更为简洁.您可以通过混合查询和方法语法来获得两全其美的效果.这通常是在LINQ to SQL查询中完成的:

Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:

var query =
  from c in db.Customers
  let totalSpend = c.Purchases.Sum (p => p.Price)    // Method syntax here
  where totalSpend > 1000
  from p in c.Purchases
  select new { p.Description, totalSpend, c.Address.State };

这篇关于流利和查询表达-相对于其他有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆