Студопедия — 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; просмотров: 403. Нарушение авторских прав; Мы поможем в написании вашей работы!



Практические расчеты на срез и смятие При изучении темы обратите внимание на основные расчетные предпосылки и условности расчета...

Функция спроса населения на данный товар Функция спроса населения на данный товар: Qd=7-Р. Функция предложения: Qs= -5+2Р,где...

Аальтернативная стоимость. Кривая производственных возможностей В экономике Буридании есть 100 ед. труда с производительностью 4 м ткани или 2 кг мяса...

Вычисление основной дактилоскопической формулы Вычислением основной дактоформулы обычно занимается следователь. Для этого все десять пальцев разбиваются на пять пар...

Условия, необходимые для появления жизни История жизни и история Земли неотделимы друг от друга, так как именно в процессах развития нашей планеты как космического тела закладывались определенные физические и химические условия, необходимые для появления и развития жизни...

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

Примеры задач для самостоятельного решения. 1.Спрос и предложение на обеды в студенческой столовой описываются уравнениями: QD = 2400 – 100P; QS = 1000 + 250P   1.Спрос и предложение на обеды в студенческой столовой описываются уравнениями: QD = 2400 – 100P; QS = 1000 + 250P...

Конституционно-правовые нормы, их особенности и виды Характеристика отрасли права немыслима без уяснения особенностей составляющих ее норм...

Толкование Конституции Российской Федерации: виды, способы, юридическое значение Толкование права – это специальный вид юридической деятельности по раскрытию смыслового содержания правовых норм, необходимый в процессе как законотворчества, так и реализации права...

Значення творчості Г.Сковороди для розвитку української культури Важливий внесок в історію всієї духовної культури українського народу та її барокової літературно-філософської традиції зробив, зокрема, Григорій Савич Сковорода (1722—1794 pp...

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