is created. Then, a query is declared in which the
objects. Thus, the type of the sequence returned by
, and these objects are created during the execution of the query.
// from a list of ContactInfo.
PART I
C h a p t e r 1 9 :
L I N Q
559
PART IPART I
public string Phone { get; set; }
public ContactInfo(string n, string a, string p) {
Name = n;
Email = a;
Phone = p;
}
}
class EmailAddress {
public string Name { get; set; }
public string Address { get; set; }
public EmailAddress(string n, string a) {
Name = n;
Address = a;
}
}
class SelectDemo3 {
static void Main() {
ContactInfo[] contacts = {
new ContactInfo("Herb", "Herb@HerbSchildt.com", "555-1010"),
new ContactInfo("Tom", "Tom@HerbSchildt.com", "555-1101"),
new ContactInfo("Sara", "Sara@HerbSchildt.com", "555-0110")
};
// Create a query that creates a list of EmailAddress objects.
var emailList = from entry in contacts
select new EmailAddress(entry.Name, entry.Email);
Console.WriteLine("The e-mail list is");
// Execute the query and display the results.
foreach(EmailAddress e in emailList)
Console.WriteLine(" {0}: {1}", e.Name, e.Address );
}
}
The output is shown here:
The e-mail list is
Herb: Herb@HerbSchildt.com
Tom: Tom@HerbSchildt.com
Sara: Sara@HerbSchildt.com
In the query, pay special attention to the
select
clause :
select new EmailAddress(entry.Name, entry.Email);
It creates a new
EmailAddress
object that contains the name and e-mail address obtained
from a
ContactInfo
object in the
contacts
array. The key point is that new
EmailAddress
objects are created by the query in its
select
clause, during the query’s execution.
www.freepdf-books.com
560
P a r t I :
T h e C # L a n g u a g e
Use Nested from Clauses
A query can contain more than one
from
clause. Thus, a query can contain nested
from
clauses. One common use of a nested
from
clause is found when a query needs to obtain
data from two different sources. Here is a simple example. It uses two
from
clauses to
iterate over two different character arrays. It produces a sequence that contains all possible
combinations of the two sets of characters.
// Use two from clauses to create a list of all
// possible combinations of the letters A, B, and C
// with the letters X, Y, and Z.
using System;
using System.Linq;
// This class holds the result of the query.
class ChrPair {
public char First;
public char Second;
public ChrPair(char c, char c2) {
First = c;
Second = c2;
}
}
class MultipleFroms {
static void Main() {
char[] chrs = { 'A', 'B', 'C' };
char[] chrs2 = { 'X', 'Y', 'Z' };
// Notice that the first from iterates over chrs and
// the second from iterates over chrs2.
var pairs = from ch1 in chrs
from ch2 in chrs2
select new ChrPair(ch1, ch2);
Console.WriteLine("All combinations of ABC with XYZ: ");
foreach(var p in pairs)
Console.WriteLine("{0} {1}", p.First, p.Second);
}
}
The output is shown here:
All combinations of ABC with XYZ:
A X
A Y
A Z
B X
B Y
www.freepdf-books.com