CHAPTER 12 LINQ TO OBJECTS
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Query Expressions *****\n");
// This array will be the basis of our testing...
ProductInfo[] itemsInStock = new[] {
new ProductInfo{ Name = "Mac's Coffee",
Description = "Coffee with TEETH",
NumberInStock = 24},
new ProductInfo{ Name = "Milk Maid Milk",
Description = "Milk cow's love",
NumberInStock = 100},
new ProductInfo{ Name = "Pure Silk Tofu",
Description = "Bland as Possible",
NumberInStock = 120},
new ProductInfo{ Name = "Cruchy Pops",
Description = "Cheezy, peppery goodness",
NumberInStock = 2},
new ProductInfo{ Name = "RipOff Water",
Description = "From the tap to your wallet",
NumberInStock = 100},
new ProductInfo{ Name = "Classic Valpo Pizza",
Description = "Everyone loves pizza!",
NumberInStock = 73}
};
// We will call various methods here!
Console.ReadLine();
}
Basic Selection Syntax
Because the syntactical correctness of a LINQ query expression is validated at compile time, you need to
remember that the ordering of these operators is critical. In the simplest terms, every LINQ query
expression is built using the from, in, and select operators. Here is the general template to follow:
var result = from matchingItem in container select matchingItem;
The item after the from operator represents an item that matches the LINQ query criteria, which can
be named anything you choose. The item after the in operator represents the data container to search
(an array, collection, XML document, etc.).
Here is a very simple query, doing nothing more than selecting every item in the container (similar
in behavior to a database Select * SQL statement). Consider the following:
static void SelectEverything(ProductInfo[] products)
{
// Get everything!
Console.WriteLine("All product details:");
var allProducts = from p in products select p;
foreach (var prod in allProducts)
{
459