Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






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 method to 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.

 


Date: 2015-02-03; view: 759


<== previous page | next page ==>
Task 1 – Declaring Extension Methods | Task 1 – Creating Anonymous Types
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.007 sec.)