This blog is moved to
http://amalhashim.wordpress.com

Friday, May 22, 2009

Linq and C# - Part 2

Linq queries with Restriction Operators

1=>


Prints each element of an input integer array whose value is less than 5.

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0);

var lowNums = from n in numbers
where n < 5 select n;

foreach(var x in lowNums) {
Console.WriteLine(x);
}

2=>

class Product {
string ProducName { get; set; }
int Units { get; set; }
int Price { get; set; }
}

Listing of all products that are out of stock.

// Fill products

var soldOutProducts = from p in products
where p.Units == 0
select p;

foreach(var pr in soldOutProducts) {
Console.WriteLine(pr.Name);
}

3=>

Lists all expensive items in stock.

var expensiveInStockProducts =
from p in products
where p.Units > 0 && p.Price > 3

foreach (var product in expensiveInStockProducts) {
Console.WriteLine(product.Name);
}

4=>

This sample uses an indexed Where clause to print the name of each number, from 0-9, where the length of the number's name is shorter than its value. In this case, the code is passing a lamda expression which is converted to the appropriate delegate type. The body of the lamda expression tests whether the length of the string is less than its index in the array.

string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

var shortDigits = digits.Where((digit, index) => digit.Length < index);

Console.WriteLine("Short digits:");
foreach (var d in shortDigits) {
Console.WriteLine("The word {0} is shorter than its value.", d);
}

No comments: