Linq provides two inquiries: smooth grammar and query expression syntax. Both can achieve query operations, but they are different in the applicable scenarios.
Flunt Syntax
The smooth grammar is similar to C#, and the query is built through the method chain. For simple queries, it is usually more concise and can access all query operators.
Query Expression Syntax
Query expression syntax is similar to SQL, which is easier to read and use. It performs well in the scenario that requires multiple range variables, such as using "Let" keywords, multiple generators or connection querys. Example: Multiple range variables
The following is an example of using query expression syntax:
Use smooth grammar, you need to write this way:
Obviously, in the absence of multiple range variables, querying the expression syntax is clearer and easy to understand.
<code class="language-csharp">from fullName in fullNames from name in fullName.Split() orderby fullName, name select name + " came from " + fullName;</code>
Mixed use
<code class="language-csharp">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);</code>
In order to combine the advantages of the two grammar, they can be mixed in Linq query. For example:
This example uses method grammar in the "SUM" operation, while retaining the readability of the inquiry expression syntax in the overall query. The grammar choice depends on the specific scenario and personal preferences. The flexible use of the two grammar can improve the readability and efficiency of the code.
The above is the detailed content of Fluent Syntax vs. Query Expression in LINQ: When Should I Use Which?. For more information, please follow other related articles on the PHP Chinese website!