Книга: C# 2008 Programmer

Query Syntax versus Method Syntax and Lambda Expressions

Query Syntax versus Method Syntax and Lambda Expressions

The two LINQ queries in the previous section use the query syntax, which is written in a declarative manner, like this:

var oddNums = from n in nums
 where (n % 2 == 1) orderby n descending
 select n;

In addition to using the query syntax, you can also use the method syntax, which is written using method calls like Where and Select, like this:

int[] nums = {
 12, 34, 10, 3, 45, 6, 90, 22, 87, 49, 13, 32
IEnumerable<int> oddNums =
 nums.Where(n => n % 2 == 1).OrderByDescending(n => n);

To find the total number of odd numbers in the array, you can also use the method syntax to query the array directly, like this:

int count =
 (nums.Where(n => n % 2 == 1).OrderBy(n => n)).Count();

Let's take a look at method syntax and how it works. First, the expression:

(n => n % 2 == 1)

is known as the lambda expression. The => is the lambda operator. You read it as "goes to," so this expression reads as "n goes to n modulus 2 equals to 1." Think of this lambda expression as a function that accepts a single input parameter, contains a single statement, and returns a value, like this:

static bool function(int n) {
 return (n % 2 == 1);

The compiler automatically infers the type of n (which is int in this case because nums is an int array) in the lambda expression. However, you can also explicitly specify the type of n, like this:

IEnumerable<int> oddNums =
 nums.Where((int n) => n % 2 == 1).OrderByDescending(n => n);

The earlier example of the string array can also be rewritten using the method syntax as follows:

string[] allNames = new string[] {
 "Jeffrey", "Kirby", "Gabriel",
 "Philip", "Ross", "Adam",
 "Alston", "Warren", "Garfield"
var foundNames =
 allNames.Where(name = name.StartsWith("G") &&

Which syntax should you use? Here's some information regarding the two syntaxes:

? There is no performance difference between the method syntax and the query syntax.

? The query syntax is much more readable, so use it whenever possible.

? Use the method syntax for cases where there is no query syntax equivalent. For example, the Count and Max methods have no query equivalent syntax.

Оглавление книги

Генерация: 1.057. Запросов К БД/Cache: 3 / 1
Вверх Вниз