15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Querying the Database ❘ OC273<br />

foreach (Product item in query)<br />

{<br />

Console.WriteLine(item.ProductID + " | " + item.ProductName);<br />

}<br />

}<br />

}<br />

}<br />

Console.ReadLine();<br />

code download ConsoleApplication1.sln<br />

In this case, a query object (again, a Table object) is populated with the query value of from<br />

p in dc.Products select p;. This comm<strong>and</strong>, though shown on two lines for readability purposes, can<br />

also be presented on a single line if you wish.<br />

query expressions in detail<br />

You will find that there are a number of query expressions that you can use from your code. The previous<br />

example is a simple select statement that returns the entire table. The following list of items are some of the<br />

other query expressions that you have at your disposal.<br />

segmenTaTion<br />

Project<br />

Filter<br />

Test<br />

Join<br />

Group<br />

Aggregate<br />

Partition<br />

Set<br />

Order<br />

xynTaX<br />

select <br />

where , distinct<br />

any(), all()<br />

join on equals <br />

group by , into , group join on<br />

equals into <br />

count([]), sum(), min(), max(),<br />

avg()<br />

skip [while] , take [while] <br />

union, intersect, except<br />

order by , [ascending | descending]<br />

filtering using expressions<br />

In addition to straight queries for the entire table, you can filter items using the where <strong>and</strong> distinct<br />

options. The following provides an example of querying the Products table for a specific type of record:<br />

var query = from p in dc.Products<br />

where p.ProductName.StartsWith("L")<br />

select p;<br />

In this case, this query is selecting all the records from the Products table that start with the letter L. This<br />

is done via the where p.ProductName.StartsWith(“L”) expression. You will find a large selection of<br />

methods available from the ProductName property that allows you to fine-tune the filtering you need. This<br />

operation produces the following results:<br />

65 | Louisiana Fiery Hot Pepper Sauce<br />

66 | Louisiana Hot Spiced Okra<br />

67 | Laughing Lumberjack Lager<br />

74 | Longlife Tofu<br />

76 | Lakkalikööri<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!