Task 2 –Querying with in-Memory Collections
The new standard query operators are in the System.Linq namespace and are provided by the System.Core.dll assembly.
1. Create a method that will be used to query in this task and call it in the Main method: static void Query() { }
static void Main(string[] args) { Query(); }
2. Recall in Exercise 5 you wrote a simple method that prints only the customers in London. Now build a simple query to do the same with stores. Replace the foreach line with: static void Query() { var stores = CreateStores(); foreach (var store in stores.Where(s => s.City=="London")) Console.WriteLine(store); } 3. Press Ctrl+F5 to build and run the code to see all the stores located in London. Press any key to terminate the application.
This example utilizes lambda expressions as well as a basic query to only select a specific set of data in the list to be run through the loop. 4. Notice the previous query used the Where method. LINQ provides an easier way of writing queries. This next piece of code provides the basic query structure provided in C# 3.0. Make the following changes in Query to see this new structure.
static void Query() { var stores = CreateStores(); IEnumerable<Store> results = from s in stores where s.City == "London" select s;
foreach (var s in results) Console.WriteLine(s); }
5. Press Ctrl+F5 to build and run the code and verify the results still show the same stores located in London. Now press any key to terminate the application.
The type returned from the query is explicitly stated here to show you what the type is, however this is not needed and we could have simply used var. The upcoming tasks will use the implicity typed local variable, var.
|