Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 20 Querying In-Memory Data by Using Query Expressions

381

{FirstName = Donna, LastName = Carreras, Country = United States }

{FirstName = Janet, LastName = Gates, Country = Canada }

{FirstName = Lucy, LastName = Harrington, Country = United Kingdom }

{FirstName = David, LastName = Liu, Country = United States }

{FirstName = Donald, LastName = Blanton, Country = United Kingdom }

{FirstName = Jackie, LastName = Blackwell, Country = Canada }

{FirstName = Elsa, LastName = Leavitt, Country = United Kingdom }

{FirstName = Eric, LastName = Lang, Country = United Kingdom }

Note It is important to remember that collections in memory are not the same as tables in a relational database and that the data that they contain is not subject to the same data integrity constraints. In a relational database, it could be acceptable to assume that every customer had a corresponding company and that each company had its own unique address. Collections do not

enforce the same level of data integrity, meaning that you could quite easily have a customer referencing a company that does not exist in the addresses array, and you might even have the same company occurring more than once in the addresses array. In these situations, the results

that you obtain might be accurate but unexpected. Join operations work best when you fully understand the relationships between the data you are joining.

Using Query Operators

The preceding sections have shown you many of the features available for querying inmemory data by using the extension methods for the Enumerable class defined in the System.Linq namespace. The syntax makes use of several advanced C# language features, and

the resultant code can sometimes be quite hard to understand and maintain. To relieve you of some of this burden, the designers of C# added query operators to the language to enable you to employ LINQ features by using a syntax more akin to SQL.

As you saw in the examples shown earlier in this chapter, you can retrieve the first name for each customer like this:

IEnumerable<string> customerFirstNames = customers.Select(cust => cust.FirstName);

You can rephrase this statement by using the from and select query operators, like this:

var customerFirstNames = from cust in customers select cust.FirstName;

At compile time, the C# compiler resolves this expression into the corresponding Select method. The from operator defines an alias for the source collection, and the select opera-

tor specifies the fields to retrieve by using this alias. The result is an enumerable collection of customer first names. If you are familiar with SQL, notice that the from operator occurs before the select operator.

382 Part III Creating Components

Continuing in the same vein, to retrieve the first and last name for each customer, you can

use the following statement. (You might want to refer to the earlier example of the same statement based on the Select extension method.)

var customerNames = from c in customers

select new { c.FirstName, c.LastName };

You use the where operator to filter data. The following example shows how to return the names of the companies based in the United States from the addresses array:

var usCompanies = from a in addresses

where String.Equals(a.Country, “United States”) select a.CompanyName;

To order data, use the orderby operator, like this:

var companyNames = from a in addresses orderby a.CompanyName select a.CompanyName;

You can group data by using the group operator:

var companiesGroupedByCountry = from a in addresses group a by a.Country;

Notice that, as with the earlier example showing how to group data, you do not provide the select operator, and you can iterate through the results by using exactly the same code as the

earlier example, like this:

foreach (var companiesPerCountry in companiesGroupedByCountry)

{

Console.WriteLine(“Country: {0}\t{1} companies”, companiesPerCountry.Key, companiesPerCountry.Count());

foreach (var companies in companiesPerCountry)

{

Console.WriteLine(“\t{0}”, companies.CompanyName);

}

}

You can invoke the summary functions, such as Count, over the collection returned by an enumerable collection, like this:

int numberOfCompanies = (from a in addresses

select a.CompanyName).Count();

Notice that you wrap the expression in parentheses. If you want to ignore duplicate values, use the Distinct method, like this:

int numberOfCountries = (from a in addresses

select a.Country).Distinct().Count();

Chapter 20 Querying In-Memory Data by Using Query Expressions

383

Tip In many cases, you probably want to count just the number of rows in a collection rather than the number of values in a field across all the rows in the collection. In this case, you can invoke the Count method directly over the original collection, like this:

int numberOfCompanies = addresses.Count();

You can use the join operator to combine two collections across a common key. The following example shows the query returning customers and addresses over the CompanyName

column in each collection, this time rephrased using the join operator. You use the on clause with the equals operator to specify how the two collections are related. (LINQ currently

supports equi-joins only.)

var citiesAndCustomers = from a in addresses join c in customers

on a.CompanyName equals c.CompanyName

select new { c.FirstName, c.LastName, a.Country };

Note In contrast with SQL, the order of the expressions in the on clause of a LINQ expression is

important. You must place the item you are joining from (referencing the data in the collection in the from clause) to the left of the equals operator and the item you are joining with (referencing

the data in the collection in the join clause) to the right.

LINQ provides a large number of other methods for summarizing information, joining,

grouping, and searching through data; this section has covered just the most common features. For example, LINQ provides the Intersect and Union methods, which you can use to

perform setwide operations. It also provides methods such as Any and All that you can use to determine whether at least one item in a collection or every item in a collection matches a specified predicate. You can partition the values in an enumerable collection by using the Take and Skip methods. For more information, see the documentation provided with Visual Studio 2008.

Querying Data in Tree<TItem> Objects

The examples you’ve seen so far in this chapter have shown how to query the data in an

array. You can use exactly the same techniques for any collection class that implements the IEnumerable interface. In the following exercise, you will define a new class for modeling employees for a company. You will create a BinaryTree object containing a collection of Employee objects, and then you will use LINQ to query this information. You will initially

call the LINQ extension methods directly, but then you will modify your code to use query operators.

384

Part III Creating Components

Retrieve data from a BinaryTree by using the extension methods

1.Start Visual Studio 2008 if it is not already running.

2.Open the QueryBinaryTree solution, located in the \Microsoft Press\Visual CSharp Step

by Step\Chapter 20\QueryBinaryTree folder in your Documents folder. The project contains the Program.cs file, which defines the Program class with the Main and Entrance methods that you have seen in previous exercises.

3.In Solution Explorer, right-click the QueryBinaryTree project, point to Add, and then click

Class. In the Add New Item—Query BinaryTree dialog box, type Employee.cs in the

Name box, and then click Add.

4.Add the automatic properties shown here in bold to the Employee class:

class Employee

{

public string FirstName { get; set; } public string LastName { get; set; } public string Department { get; set; } public int Id { get; set; }

}

5.Add the ToString method shown here in bold to the Employee class. Classes in the .NET

Framework use this method when converting the object to a string representation, such as when displaying it by using the Console.WriteLine statement.

class Employee

{

...

public override string ToString()

{

return String.Format(“Id: {0}, Name: {1} {2}, Dept: {3}”, this.Id, this.FirstName, this.LastName, this.Department);

}

}

6.Modify the definition of the Employee class in the Employee.cs file to implement the IComparable<Employee> interface, as shown here:

class Employee : IComparable<Employee>

{

}

This step is necessary because the BinaryTree class specifies that its elements must be “comparable.”

7.Right-click the IComparable<Employee> interface in the class definition, point to

Implement Interface, and then click Implement Interface Explicitly.

Chapter 20 Querying In-Memory Data by Using Query Expressions

385

This action generates a default implementation of the CompareTo method. Remember that the BinaryTree class calls this method when it needs to compare elements when

inserting them into the tree.

8.Replace the body of the CompareTo method with the code shown here in bold. This implementation of the CompareTo method compares Employee objects based on the value of the Id field.

int IComparable<Employee>.CompareTo(Employee other)

{

if (other == null) return 1;

if (this.Id > other.Id) return 1;

if (this.Id < other.Id) return -1;

return 0;

}

Note For a description of the IComparable interface, refer to Chapter 18, “Introducing Generics.”

9.In Solution Explorer, right-click the QueryBinaryTree solution, point to Add, and then click Existing Project. In the Add Existing Project dialog box, move to the folder

Microsoft Press\Visual CSharp Step By Step\Chapter 20\BinaryTree in your Documents folder, click the BinaryTree project, and then click Open.

The BinaryTree project contains a copy of the enumerable BinaryTree class that you implemented in Chapter 19.

10.In Solution Explorer, right-click the QueryBinaryTree project, and then click Add Reference. In the Add Reference dialog box, click the Projects tab, select the BinaryTree project, and then click OK.

11.In Solution Explorer, open the Program.cs file, and verify that the list of using statements at the top of the file includes the following line of code:

using System.Linq;

12.Add the following using statement to the list at the top of the Program.cs file to bring the BinaryTree namespace into scope:

using BinaryTree;

386Part III Creating Components

13.In the Entrance method in the Program class, add the following statements shown in bold type to construct and populate an instance of the BinaryTree class:

static void Entrance()

{

Tree<Employee> empTree = new Tree<Employee>(new Employee

{Id = 1, FirstName = “Janet”, LastName = “Gates”, Department = “IT”}); empTree.Insert(new Employee

{Id = 2, FirstName = “Orlando”, LastName = “Gee”, Department = “Marketing”}); empTree.Insert(new Employee

{Id = 4, FirstName = “Keith”, LastName = “Harris”, Department = “IT” }); empTree.Insert(new Employee

{Id = 6, FirstName = “Lucy”, LastName = “Harrington”, Department = “Sales” }); empTree.Insert(new Employee

{Id = 3, FirstName = “Eric”, LastName = “Lang”, Department = “Sales” }); empTree.Insert(new Employee

{Id = 5, FirstName = “David”, LastName = “Liu”, Department = “Marketing” });

}

14.Add the following statements shown in bold to the end of the Entrance method. This code uses the Select method to list the departments found in the binary tree.

static void Entrance()

{

...

Console.WriteLine(“List of departments”);

var depts = empTree.Select(d => d.Department);

foreach (var dept in depts) Console.WriteLine(“Department: {0}”, dept);

}

15.On the Debug menu, click Start Without Debugging.

The application should output the following list of departments:

List of departments

Department: IT

Department: Marketing

Department: Sales

Department: IT

Department: Marketing

Department: Sales

Each department occurs twice because there are two employees in each department. The order of the departments is determined by the CompareTo method of the Employee class, which uses the Id property of each employee to sort the data. The first

department is for the employee with the Id value 1, the second department is for the employee with the Id value 2, and so on.

16. Press Enter to return to Visual Studio 2008.

Chapter 20 Querying In-Memory Data by Using Query Expressions

387

17.Modify the statement that creates the enumerable collection of departments as shown here in bold:

var depts = empTree.Select(d => d.Department).Distinct();

The Distinct method removes duplicate rows from the enumerable collection.

18.On the Debug menu, click Start Without Debugging.

Verify that the application now displays each department only once, like this:

List of departments

Department: IT

Department: Marketing

Department: Sales

19.Press Enter to return to Visual Studio 2008.

20.Add the following statements to the end of the Entrance method. This block of code uses the Where method to filter the employees and return only those in the IT department. The Select method returns the entire row rather than projecting specific columns.

Console.WriteLine(“\nEmployees in the IT department”); var ITEmployees =

empTree.Where(e => String.Equals(e.Department, “IT”)).Select(emp => emp);

foreach (var emp in ITEmployees) Console.WriteLine(emp);

21.Add the code shown here to the end of the Entrance method, after the code from the preceding step. This code uses the GroupBy method to group the employees found in the binary tree by department. The outer foreach statement iterates through each group, displaying the name of the department. The inner foreach statement displays the names of the employees in each department.

Console.WriteLine(“\nAll employees grouped by department”); var employeesByDept = empTree.GroupBy(e => e.Department);

foreach (var dept in employeesByDept)

{

Console.WriteLine(“Department: {0}”, dept.Key); foreach (var emp in dept)

{

Console.WriteLine(“\t{0} {1}”, emp.FirstName, emp.LastName);

}

}

388Part III Creating Components

22.On the Debug menu, click Start Without Debugging. Verify that the output of the application looks like this:

List of departments

Department: IT

Department: Marketing

Department: Sales

Employees in the IT department

Id: 1, Name: Janet Gates, Dept: IT

Id: 4, Name: Keith Harris, Dept: IT

All employees grouped by department

Department: IT

Janet Gates

Keith Harris

Department: Marketing

Orlando Gee

David Liu

Department: Sales

Eric Lang

Lucy Harrington

23. Press Enter to return to Visual Studio 2008.

Retrieve data from a BinaryTree by using query operators

1.In the Entrance method, comment out the statement that generates the enumerable

collection of departments, and replace it with the following statement shown in bold, based on the from and select query operators:

//var depts = empTree.Select(d => d.Department).Distinct(); var depts = (from d in empTree

select d.Department).Distinct();

2.Comment out the statement that generates the enumerable collection of employees in the IT department, and replace it with the following code shown in bold:

//var ITEmployees =

// empTree.Where(e => String.Equals(e.Department, “IT”)).Select(emp => emp); var ITEmployees = from e in empTree

where String.Equals(e.Department, “IT”) select e;

3.Comment out the statement that generates the enumerable collection grouping employees by department, and replace it with the statement shown here in bold:

//var employeesByDept = empTree.GroupBy(e => e.Department); var employeesByDept = from e in empTree

group e by e.Department;

4.On the Debug menu, click Start Without Debugging. Verify that the output of the application is the same as before.

5.Press Enter to return to Visual Studio 2008.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]