Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Task 1 – Creating Anonymous Types

 

1. Modify the Query method to loop through customers and stores to find all the stores for each customer that are located in the same city.

static void Query()

{

foreach (var c in CreateCustomers())

{

var customerStores = new //Anonymous Type Creation:

{ //Mouse over the var in this

CustomerID = c.CustomerID, //statement to see the type

City = c.City,

CustomerName = c.Name,

Stores = from s in CreateStores()

where s.City == c.City

select s

};

 

Console.WriteLine("{0}\t{1}",

customerStores.City, customerStores.CustomerName);

 

foreach (var store in customerStores.Stores)

Console.WriteLine("\t<{0}>", store.Name);

}

}

 

Notice the type of customerStores does not have a name. If you mouse over the var it says it is of type AnonymousType 'a . The structure is also provided; the three properties of this new type are CustomerID, CustomerName, City, and Stores.

 

2. Press Ctrl+F5 to build and run the application and print the customers and their associated orders. Now terminate the application by pressing any key.

 

In the previous code, the names of the anonymous type members (CustomerName, City, Stores, and CustomerID) are explicitly specified. It is also possible to omit the names, in which case, the names of the generated members are the same as the members used to initialize them. This is called a projection initializer.

 

3. Change the foreach body to omit the property names of the anonymous class:

 

static void Query()

{

foreach (var c in CreateCustomers())

{

var customerStores = new //Anonymous Type Creation:

{ //Mouse over the var in this

c.CustomerID, //statement to see the type

c.City,

CustomerName = c.Name,

Stores = from s in CreateStores()

where s.City == c.City

select s

};

 

Console.WriteLine("{0}\t{1}",

customerStores.City, customerStores.CustomerName);

 

foreach (var store in customerStores.Stores)

Console.WriteLine("\t<{0}>", store.Name);

}

}

 

 

4. Press Ctrl+F5 to build run the application and notice the output is the same. Then press any key to terminate the application.



Date: 2015-02-03; view: 722


<== previous page | next page ==>
Task 1 – Understanding Lambda Expressions | Task 2 – Additional Query Expressions Using Anonymous Types
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.006 sec.)