Студопедия Главная Случайная страница Обратная связь

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

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




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


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


ТЕОРЕТИЧЕСКАЯ МЕХАНИКА Статика является частью теоретической механики, изучающей условия, при ко­торых тело находится под действием заданной системы сил...


Теория усилителей. Схема Основная масса современных аналоговых и аналого-цифровых электронных устройств выполняется на специализированных микросхемах...

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

Тактические действия нарядов полиции по предупреждению и пресечению групповых нарушений общественного порядка и массовых беспорядков В целях предупреждения разрастания групповых нарушений общественного порядка (далееГНОП) в массовые беспорядки подразделения (наряды) полиции осуществляют следующие мероприятия...

Механизм действия гормонов а) Цитозольный механизм действия гормонов. По цитозольному механизму действуют гормоны 1 группы...

Понятие о синдроме нарушения бронхиальной проходимости и его клинические проявления Синдром нарушения бронхиальной проходимости (бронхообструктивный синдром) – это патологическое состояние...

Опухоли яичников в детском и подростковом возрасте Опухоли яичников занимают первое место в структуре опухолей половой системы у девочек и встречаются в возрасте 10 – 16 лет и в период полового созревания...

Способы тактических действий при проведении специальных операций Специальные операции проводятся с применением следующих основных тактических способов действий: охрана...

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