Restriction Operators
Where - Simple 1
This sample uses the where clause to find all elements of an array with a value less than 5.
Code:
public void Linq1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums = numbers.Where(num => num < 5);
Log.WriteLine("Numbers < 5:");
foreach (var x in lowNums)
{
Log.WriteLine(x);
}
}
Result:
Where - Simple 2
This sample uses the where clause to find all products that are out of stock.
Code:
public void Linq2()
{
List products = GetProductList();
var soldOutProducts = products.Where(prod => prod.UnitsInStock == 0);
Log.WriteLine("Sold out products:");
foreach (var product in soldOutProducts)
{
Log.WriteLine("{0} is sold out!", product.ProductName);
}
}
Result:
Where - Simple 3
This sample uses the where clause to find all products that are in stock and cost more than 3.00 per unit.
Code:
public void Linq3()
{
List products = GetProductList();
var expensiveInStockProducts = products.Where(prod => prod.UnitsInStock > 0 && prod.UnitPrice > 3.00M);
Log.WriteLine("In-stock products that cost more than 3.00:");
foreach (var product in expensiveInStockProducts)
{
Log.WriteLine("{0} is in stock and costs more than 3.00.", product.ProductName);
}
}
Result:
Where - Drilldown
This sample uses the where clause to find all customers in Washington and then it uses a foreach loop to iterate over the orders collection that belongs to each customer.
Code:
public void Linq4()
{
List customers = GetCustomerList();
var waCustomers = customers.Where(cust => cust.Region == "WA");
Log.WriteLine("Customers from Washington and their orders:");
foreach (var customer in waCustomers)
{
Log.WriteLine("Customer {0}: {1}", customer.CustomerID, customer.CompanyName);
foreach (var order in customer.Orders)
{
Log.WriteLine(" Order {0}: {1}", order.OrderID, order.OrderDate);
}
}
}
Result:
Where - Indexed
This sample demonstrates an indexed where clause that returns digits whose name is shorter than their value.
Code:
public void Linq5()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var shortDigits = digits.Where((digit, index) => digit.Length < index);
Log.WriteLine("Short digits:");
foreach (var d in shortDigits)
{
Log.WriteLine("The word {0} is shorter than its value.", d);
}
}
Result: