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



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

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

Расчетные и графические задания Равновесный объем - это объем, определяемый равенством спроса и предложения...

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

Кишечный шов (Ламбера, Альберта, Шмидена, Матешука) Кишечный шов– это способ соединения кишечной стенки. В основе кишечного шва лежит принцип футлярного строения кишечной стенки...

Принципы резекции желудка по типу Бильрот 1, Бильрот 2; операция Гофмейстера-Финстерера. Гастрэктомия Резекция желудка – удаление части желудка: а) дистальная – удаляют 2/3 желудка б) проксимальная – удаляют 95% желудка. Показания...

Ваготомия. Дренирующие операции Ваготомия – денервация зон желудка, секретирующих соляную кислоту, путем пересечения блуждающих нервов или их ветвей...

ПРОФЕССИОНАЛЬНОЕ САМОВОСПИТАНИЕ И САМООБРАЗОВАНИЕ ПЕДАГОГА Воспитывать сегодня подрастающее поколение на со­временном уровне требований общества нельзя без по­стоянного обновления и обогащения своего профессио­нального педагогического потенциала...

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

Мотивационная сфера личности, ее структура. Потребности и мотивы. Потребности и мотивы, их роль в организации деятельности...

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