Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 21 INTRODUCTION TO LINQ

The select . . . group Clause

There are two types of clauses that make up the select...group section—the select clause and the group...by clause. While the clauses that precede the select...group section specify the data sources and which objects to choose, the select...group section does the following:

The select clause specifies which parts of the chosen objects should be selected. It can specify any of the following:

The entire data item

A field from the data item

A new object comprising several fields from the data item (or any other value, for that matter).

The group...by clause is optional and specifies how the chosen items should be grouped. We’ll cover the group...by clause later in the chapter.

Figure 21-10 shows the syntax for the select...group clause.

Figure 21-10. The syntax of the select . . . group clause

558

CHAPTER 21 INTRODUCTION TO LINQ

The following code shows an example of using the select clause to select the entire data item. First, the program creates an array of objects of an anonymous type. The query expression then uses the select statement to select each item in the array.

using System;

 

 

 

using System.Linq;

 

 

class Program {

 

 

 

static void

Main() {

 

 

var students = new[]

// Array of objects of an anonymous type

{

 

 

 

new {

LName="Jones",

FName="Mary",

Age=19, Major="History" },

new {

LName="Smith",

FName="Bob",

Age=20, Major="CompSci" },

new { LName="Fleming", FName="Carol", Age=21, Major="History" }

};

var query = from s in students select s;

foreach (var q in query) Console.WriteLine("{0}, {1}: Age {2}, {3}",

q.LName, q.FName, q.Age, q.Major);

}

}

This code produces the following output:

Jones, Mary: Age 19, History

Smith, Bob: Age 20, CompSci

Fleming, Carol: Age 21, History

You can also use the select clause to choose only particular fields of the object. For example, the select clause in the following code selects only the last name of the student.

var query = from s in students select s.LName;

foreach (var q in query) Console.WriteLine(q);

When you substitute these two statements for the corresponding two statements in the preceding full example, the program produces the following output:

Jones

Smith

Fleming

559

CHAPTER 21 INTRODUCTION TO LINQ

Anonymous Types in Queries

The result of a query can consist of items from the source collections, fields from the items in the source collections, or anonymous types.

You can create an anonymous type in a select clause by placing curly braces around a commaseparated list of fields you want to include in the type. For example, to make the code in the previous section select just the names and majors of the students, you could use the following syntax:

select new { s.LastName, s.FirstName, s.Major };

Anonymous type

The following code creates an anonymous type in the select clause and uses it later in the WriteLine statement.

using System; using System.Linq;

class Program {

 

 

 

static void

Main()

 

 

{

 

 

 

var students = new[]

// Array of objects of an anonymous type

{

 

 

 

new {

LName="Jones",

FName="Mary",

Age=19, Major="History" },

new {

LName="Smith",

FName="Bob",

Age=20, Major="CompSci" },

new {

LName="Fleming", FName="Carol", Age=21, Major="History" }

};

 

 

 

 

var query = from s in students

 

select new { s.LName, s.FName, s.Major };

 

 

 

 

 

 

 

Create anonymous type

 

foreach (var q in query)

 

Console.WriteLine("{0} {1} -- {2}",

 

 

q.FName, q.LName, q.Major );

}

 

 

 

}

 

 

Access fields of anonymous type

This code produces the following output:

Mary Jones -- History

Bob Smith -- CompSci

Carol Fleming -- History

560

CHAPTER 21 INTRODUCTION TO LINQ

The group Clause

The group clause groups the selected objects according to some criterion. For example, with the array of students in the previous examples, the program could group the students according to their majors.

The important things to know about the group clause are the following:

When items are included in the result of the query, they’re placed in groups according to the value of a particular field. The value on which items are grouped is called the key.

Unlike the select clause, the group clause does not return an enumerable that can enumerate the items from the original source. Instead, it returns an enumerable that enumerates the groups of items that have been formed.

The groups themselves are enumerable and can enumerate the actual items.

An example of the syntax of the group clause is the following:

group student by student.Major;

Keyword

Keyword

For example, the following code groups the students according to their majors:

static void

Main( )

 

 

{

 

 

 

var students = new[]

// Array of objects of an anonymous type

{

 

 

 

new {

LName="Jones",

FName="Mary",

Age=19, Major="History" },

new {

LName="Smith",

FName="Bob",

Age=20, Major="CompSci" },

new {

LName="Fleming",

FName="Carol", Age=21, Major="History" }

};

 

 

 

var query = from student in students

group student by student.Major;

foreach (var s in query) // Enumerate the groups.

{

Console.WriteLine("{0}", s.Key);

 

 

 

 

Grouping key

foreach (var t in s)

 

 

// Enumerate the items in the group.

Console.WriteLine("

 

{0}, {1}", t.LName, t.FName);

}

 

 

 

}

 

 

 

561

CHAPTER 21 INTRODUCTION TO LINQ

This code produces the following output:

History

Jones, Mary

Fleming, Carol

CompSci

Smith, Bob

Figure 21-11 illustrates the object that is returned from the query expression and stored in the query variable.

The object returned from the query expression is an enumerable that enumerates the groups resulting from the query.

Each group is distinguished by a field called Key.

Each group is itself enumerable and can enumerate its items.

Figure 21-11. The group clause returns a collection of collections of objects rather than a collection

of objects.

562

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