PART I
C h a p t e r 1 9 :
L I N Q
567
PART IPART I
The following program creates a class called
Item
, which encapsulates an item’s name
with its number. It creates another class called
InStockStatus
, which links an item number
with a Boolean property that indicates whether or not the item is in stock. It also creates a
class called
Temp
, which has two fields: one
string
and one
bool
. Objects of this class will
hold the result of the query. The query uses
join
to produce a list in which an item’s name
is associated with its in-stock status.
// Demonstrate join.
using System;
using System.Linq;
// A class that links an item name with its number.
class Item {
public string Name { get; set; }
public int ItemNumber { get; set; }
public Item(string n, int inum) {
Name = n;
ItemNumber = inum;
}
}
// A class that links an item number with its in-stock status.
class InStockStatus {
public int ItemNumber { get; set; }
public bool InStock { get; set; }
public InStockStatus(int n, bool b) {
ItemNumber = n;
InStock = b;
}
}
// A class that encapsulates a name with its status.
class Temp {
public string Name { get; set; }
public bool InStock { get; set; }
public Temp(string n, bool b) {
Name = n;
InStock = b;
}
}
class JoinDemo {
static void Main() {
Item[] items = {
new Item("Pliers", 1424),
new Item("Hammer", 7892),
new Item("Wrench", 8534),
new Item("Saw", 6411)
};
www.freepdf-books.com
568
P a r t I :
T h e C # L a n g u a g e
InStockStatus[] statusList = {
new InStockStatus(1424, true),
new InStockStatus(7892, false),
new InStockStatus(8534, true),
new InStockStatus(6411, true)
};
// Create a query that joins Item with InStockStatus to
// produce a list of item names and availability. Notice
// that a sequence of Temp objects is produced.
var inStockList = from item in items
join entry in statusList
on item.ItemNumber equals entry.ItemNumber
select new Temp(item.Name, entry.InStock);
Console.WriteLine("Item\tAvailable\n");
// Execute the query and display the results.
foreach(Temp t in inStockList)
Console.WriteLine("{0}\t{1}", t.Name, t.InStock);
}
}
The output is shown here:
Item Available
Pliers True
Hammer False
Wrench True
Saw True
To understand how
join
works, let’s walk through each line in the query. The query
begins in the normal fashion with this
from
clause:
var inStockList = from item in items
This clause specifies that
item
is the range variable for the data source specified by
Do'stlaringiz bilan baham: |