Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 21 INTRODUCTION TO LINQ

Example Using a Lambda Expression Parameter

The previous example used a separate method and a delegate to attach the code to the operator. This required declaring the method, declaring the delegate object, and then passing the delegate object to the operator. This works fine and is exactly the right approach to take if either of the following conditions is true:

If the method must be called from somewhere else in the program than just in the place it’s used to initialize the delegate object

If the code in the method body is more than just a statement or two long

If neither of these conditions is true, however, you probably want to use a more compact and localized method of supplying the code to the operator, using a lambda expression as described in Chapter 15.

We can modify the previous example to use a lambda expression by first deleting the IsOdd method entirely and placing the equivalent lambda expression directly at the declaration of the delegate object. The new code is shorter and cleaner and looks like this:

class Program

{

static void Main()

{

int[] intArray = new int[] { 3, 4, 5, 6, 7, 9 };

Lambda expression

var countOdd = intArray.Count( x => x % 2 == 1 );

Console.WriteLine("Count of odd numbers: {0}", countOdd);

}

}

Like the previous example, this code produces the following output:

Count of odd numbers: 4

573

CHAPTER 21 INTRODUCTION TO LINQ

We could also have used an anonymous method in place of the lambda expression, as shown following. This is more verbose, though, and since lambda expressions are equivalent semantically and are less verbose, there’s little reason to use anonymous methods anymore.

class Program

{

static void Main( )

{

int[] intArray = new int[] { 3, 4, 5, 6, 7, 9 };

Anonymous method

Func<int, bool> myDel = delegate(int x)

{

return x % 2 == 1;

};

var countOdd = intArray.Count(myDel);

Console.WriteLine("Count of odd numbers: {0}", countOdd);

}

}

574

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]