Студопедия — Task 1 – Understanding Lambda Expressions
Студопедия Главная Случайная страница Обратная связь

Разделы: Автомобили Астрономия Биология География Дом и сад Другие языки Другое Информатика История Культура Литература Логика Математика Медицина Металлургия Механика Образование Охрана труда Педагогика Политика Право Психология Религия Риторика Социология Спорт Строительство Технология Туризм Физика Философия Финансы Химия Черчение Экология Экономика Электроника

Task 1 – Understanding Lambda Expressions






A lambda expression is written as a parameter list, followed by the => token, and then an expression or statement. For example:

(int x) => { return x + 1; } // parameter list, statement

 

The parameters of a lambda expression can be explicitly or implicitly typed.

(int x) => x + 1; // explicit parameter list, expression

 

In an implicitly typed parameter list, the types of the parameters are inferred from the context in which the lambda expression is used. In addition, if a lambda expression has a single, implicitly typed parameter, the parentheses may be omitted from the parameter list:

x => x + 1; // implicit parameter list, expression

(x,y) => x * y; // implicit parameter list, expression

 

1. Suppose you wanted to find all the customers in a given city. To do this use the FindAll method from the List<T> class. First update the Main methodto call this new method and then write FindCustomersByCity which will first use C# 2.0’s anonymous method syntax, delegates.

static void Main(string[] args)

{

var customers = CreateCustomers();

 

foreach (var c in FindCustomersByCity(customers, "London"))

Console.WriteLine(c);

}

 

public static List<Customer> FindCustomersByCity(

List<Customer> customers,

string city)

{

return customers.FindAll(

delegate(Customer c){

return c.City == city;

});

}

 

2. Press Ctrl+F5 to build and run the program to test that only customers located in London are displayed. Press any key to terminate the application.

3. Now, replace the anonymous method with an equivalent lambda expression:

 

public static List<Customer> FindCustomersByCity(

List<Customer> customers,

string city)

{

return customers.FindAll(c => c.City == city);

}

 

4. Press Ctrl+F5 to build and run the program to again see the same output. Press any key to terminate the application.

 

Lambda expressions simplify the code required. Notice that in this example the parameter list consisted of ‘c’ which was implicitly typed and therefore did not require the type to be explicitly stated. If you wanted to be more explicit, the line could also have been written:

return customers.FindAll((Customer c) => c.City == city);

Task 2 – Calling a Complex Extension Method using Lambda Expressions [optional]

In this task you extend the Dictionary class by creating a generic extension method. You then see how to use lambda expressions when calling this new method.

 

1. First, set up the filter method that will be used to query over our data. Add a new delegate type to the NewLanguageFeatures namespace.

namespace NewLanguageFeatures

{

public delegate bool KeyValueFilter<K, V>(K key, V value);

 

2. Define an extension method for the Dictionary<K, V>;type in the Extensions class:

public static class Extensions

{

public static List<K> FilterBy<K,V>(

this Dictionary<K, V> items,

KeyValueFilter<K, V> filter)

{

var result = new List<K>();

 

foreach (KeyValuePair<K, V> element in items)

{

if (filter(element.Key, element.Value))

result.Add(element.Key);

}

return result;

}

 

public static List<T> Append<T>(this List<T> a, List<T> b)

{

 

This extension method takes in a dictionary and a delegate. It then iterates over all of the key value pairs in the dictionary and invokes the filter delegate for each. If the filter method returns true, then that value is added to a list and returned.

3. Replace the code in Main with the following code

 

static void Main(string[] args)

{

var customers = CreateCustomers();

var customerDictionary = new Dictionary<Customer, string>();

 

foreach (var c in customers)

customerDictionary.Add(c, c.Name.Split(' ')[1]);

 

var matches = customerDictionary.FilterBy(

(customer, lastName) => lastName.StartsWith("A"));

//The above line runs the query

Console.WriteLine("Number of Matches: {0}", matches.Count);

}

 

This code sets up a dictionary containing customers associate with their last name. It then calls the new extension method passing a lambda expression that accepts two arguments. The result is to find the number of customers in the dictionary that have a last name starting with the letter A.

 

4. Press Ctrl+F5 to build and run the program and see the number of matches; there should be two.. Then press any key to close the console window and terminate the application.

 







Дата добавления: 2015-09-07; просмотров: 395. Нарушение авторских прав; Мы поможем в написании вашей работы!



Кардиналистский и ординалистский подходы Кардиналистский (количественный подход) к анализу полезности основан на представлении о возможности измерения различных благ в условных единицах полезности...

Обзор компонентов Multisim Компоненты – это основа любой схемы, это все элементы, из которых она состоит. Multisim оперирует с двумя категориями...

Композиция из абстрактных геометрических фигур Данная композиция состоит из линий, штриховки, абстрактных геометрических форм...

Важнейшие способы обработки и анализа рядов динамики Не во всех случаях эмпирические данные рядов динамики позволяют определить тенденцию изменения явления во времени...

Основные симптомы при заболеваниях органов кровообращения При болезнях органов кровообращения больные могут предъявлять различные жалобы: боли в области сердца и за грудиной, одышка, сердцебиение, перебои в сердце, удушье, отеки, цианоз головная боль, увеличение печени, слабость...

Вопрос 1. Коллективные средства защиты: вентиляция, освещение, защита от шума и вибрации Коллективные средства защиты: вентиляция, освещение, защита от шума и вибрации К коллективным средствам защиты относятся: вентиляция, отопление, освещение, защита от шума и вибрации...

Задержки и неисправности пистолета Макарова 1.Что может произойти при стрельбе из пистолета, если загрязнятся пазы на рамке...

Характерные черты немецкой классической философии 1. Особое понимание роли философии в истории человечества, в развитии мировой культуры. Классические немецкие философы полагали, что философия призвана быть критической совестью культуры, «душой» культуры. 2. Исследовались не только человеческая...

Обзор компонентов Multisim Компоненты – это основа любой схемы, это все элементы, из которых она состоит...

Кран машиниста усл. № 394 – назначение и устройство Кран машиниста условный номер 394 предназначен для управления тормозами поезда...

Studopedia.info - Студопедия - 2014-2024 год . (0.009 сек.) русская версия | украинская версия