You may have already used a version of LINQ. If you have, there won’t be much that’s new to you in this chapter; for the most part, LINQ is LINQ. But if it’s new to you, here is the basic syntax:
Put On Your Thinking Hat
Here’s a simple entity that represents a supplier. Can you write a LINQ query that returns the entire entity where the company is in Kansas (“KS”) or Missouri (“MO”), ordered by the AddressCity
?
(HINT: To specify to selection criteria, use the standard logical operators, in this case a logical or (“||” in C# and “Or”
in Visual Basic.)
Words For The Wise
LINQ stands for LANGUAGE INTEGRATED QUERY. It’s part of C# and Visual Basic, and it’s available for F# as part of the F# Power Pack.
There are several versions of LINQ (including LINQ to Entities, which we’ll be using, LINQ to Objects, and LINQ to SQL), but one of the nice things about LINQ is that you can usually ignore which version the compiler is actually using, because the syntax is the same.
More Examples
Microsoft has compiled a marvelous resource for learning LINQ. Search for “101 LINQ Examples”. There are examples, in both C# and Visual Basic, for just about every LINQ method.
Put On Your Thinking Hat
How’d you do? It doesn’t matter if you chose something besides “s” for your variables. They’re just variables—the name doesn’t matter, as long as it makes sense to you.
var q = from s in context.Suppliers
where s.AddressState == "KS" || s.AddressState == "MO"
orderby s.AddressCity
select s;
Dim q = From s in context.Suppliers
Where s.AddressState = "KS" Or s.AddressState = "MO"
Order By s.AddressCity
Select s;