C# Fluent and Query Expression — 两者相比有什么优势吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/214500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:25:59  来源:igfitidea点击:

Fluent and Query Expression — Is there any benefit(s) of one over other?

c#linq

提问by JarrettV

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.

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

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?

两者之间有什么区别,或者两者之间有什么特别的好处吗?

采纳答案by Joe Albahari

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:

两者都不是更好:它们满足不同的需求。当您想利用多个范围变量时,查询语法就派上用场了。这发生在三种情况下:

  • When using the let keyword
  • When you have multiple generators (fromclauses)
  • When doing joins
  • 使用 let 关键字时
  • 当你有多个生成器(from子句)
  • 做连接时

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

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

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

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:

另一方面,方法语法公开了查询运算符的全部范围,并且对于简单查询更加简洁。您可以通过混合查询和方法语法来获得两全其美。这通常在 LINQ to SQL 查询中完成:

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 };

回答by Kozyarchuk

Fluent syntax does seem more powerful indeed, it should also work better for organizing code into small reusable methods.

Fluent 语法确实看起来更强大,它也应该更适合将代码组织成小的可重用方法。

回答by James Curran

The fluent interface if there's just a where. If I need a select or orderby, I generally use the Query syntax.

流畅的界面,如果只是一个地方。如果我需要 select 或 orderby,我通常使用 Query 语法。

回答by CMS

I really like the Fluent syntax and I try to use it where I can, but in certain cases, for example where I use joins, I usually prefer the Query syntax, in those cases I find it easier to read, and I think some people are more familiar to Query (SQL-like) syntax, than lambdas.

我真的很喜欢 Fluent 语法,我会尽可能地使用它,但在某些情况下,例如在我使用连接的情况下,我通常更喜欢 Query 语法,在这些情况下我发现它更容易阅读,而且我认为有些人比 lambdas 更熟悉 Query(类 SQL)语法。

回答by LizB

While I do understand and like the fluent format , I've stuck to Query for the time being for readability reasons. People just being introduced to LINQ will find Query much more comfortable to read.

虽然我确实理解并喜欢 fluent format ,但出于可读性原因,我暂时坚持使用 Query 。刚接触 LINQ 的人会发现 Query 更易于阅读。

回答by James Newton-King

Each style has their pros and cons. Query syntax is nicer when it comes to joins and it has the useful letkeyword that makes creating temporary variables inside a query easy.

每种风格都有其优点和缺点。查询语法在连接方面更好,它具有有用的let关键字,可以轻松地在查询中创建临时变量。

Fluent syntax on the other hand has a lot more methods and operations that aren't exposed through the query syntax. Also since they are just extension methods you can write your own.

另一方面,Fluent 语法具有更多未通过查询语法公开的方法和操作。此外,由于它们只是扩展方法,您可以编写自己的方法。

I have found that every time I start writing a LINQ statement using the query syntax I end up having to put it in parenthesis and fall back to using fluent LINQ extension methods. Query syntax just doesn't have enough features to use by itself.

我发现每次我开始使用查询语法编写 LINQ 语句时,我最终不得不将它放在括号中,然后回退到使用流畅的 LINQ 扩展方法。查询语法本身没有足够的功能可以使用。

回答by Jay Bazuzi

I prefer to use the latter (sometimes called "query comprehension syntax") when I can write the whole expression that way.

当我可以用这种方式编写整个表达式时,我更喜欢使用后者(有时称为“查询理解语法”)。

var titlesQuery = from e in entries
                  where e.Approved
                  orderby e.Rating
                  select e.Titles;

var title = titlesQuery.FirstOrDefault();

As soon as I have to add (parentheses) and .MethodCalls(), I change.

一旦我必须添加(括号)和.MethodCalls(),我就会改变。

When I use the former, I usually put one clause per line, like this:

当我使用前者时,我通常每行放一个子句,如下所示:

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

I find that a little easier to read.

我觉得这更容易阅读。

回答by Steve Tranby

I prefer the query syntax as I came from traditional web programming using SQL. It is much easier for me to wrap my head around. However, it think I will start to utilize the .Where(lambda) as it is definitely much shorter.

我更喜欢查询语法,因为我来自使用 SQL 的传统 Web 编程。对我来说,把头包起来要容易得多。但是,它认为我将开始使用 .Where(lambda) 因为它肯定要短得多。

回答by Instance Hunter

I don't get the query syntax at all. There's just no reason for it in my mind. let can be acheived with .Select and anonymous types. I just think things look much more organized with the "punctuation" in there.

我根本没有得到查询语法。在我看来没有任何理由。let 可以通过 .Select 和匿名类型实现。我只是认为那里的“标点符号”看起来更有条理。

回答by Antony Scott

I've been using Linq for about 6 months now. When I first started using it I preferred the query syntax as it's very similar to T-SQL.

我已经使用 Linq 大约 6 个月了。当我第一次开始使用它时,我更喜欢查询语法,因为它与 T-SQL 非常相似。

But, I'm gradually coming round to the former now, as it's easy to write reusable chunks of code as extension methods and just chain them together. Although I do find putting each clause on its own line helps a lot with readability.

但是,我现在逐渐转向前者,因为编写可重用的代码块作为扩展方法并将它们链接在一起很容易。虽然我确实发现将每个子句放在自己的行上有助于提高可读性。