Thursday, May 6, 2010

LINQ Samples (Partitioning operator) : 'TakeWhile'

Example Simple:'TakeWhile' will list all the items in a collection until it reaches the condition given .Following example show its usage.

public void TakeWhileSimple()
{
int[] num = { 34, 56, 72, 74, 223, 442, 4, 61, 40 };

Console.WriteLine("Print num ");
foreach (int j in num)
Console.Write("{0} ", j);

Console.WriteLine("\n\nPrint num(unordered) with TakeWhile until value is not < 150 ");
IEnumerable i1 = num.TakeWhile(a => a < 150);
foreach (int j in i1)
Console.Write("{0} ", j);

Console.WriteLine("\n\nPrint num (ordered) with TakeWhile until value is not < 150 ");
IEnumerable i2 = num.OrderBy(a=>a).TakeWhile(a => a < 150);
foreach (int j in i2)
Console.Write("{0} ", j);
}


OUTPUT :

Print num
34 56 72 74 223 442 4 61 40

Print num(unordered) with TakeWhile until value is not < 150
34 56 72 74

Print num (ordered) with TakeWhile until value is not < 150
4 34 40 56 61 72 74


Example Nested: In this example we are first order the list and then uses 'TakeWhile' .The output generated is equivalent to using 'Where' clause. However note that the purpose of 'TakeWhile' is complete different.

public void TakeWhileMore()
{
List prodA = new List {
new Product { productID=1, productName="Prod1", productPrice=100.50, stockQuantity= 10 },
new Product { productID=2, productName="Prod2", productPrice=129.50, stockQuantity= 15 },
new Product { productID=3, productName="Prod3", productPrice=51.00, stockQuantity= 120 },
new Product { productID=4, productName="Prod4", productPrice=79.50, stockQuantity= 30 },
new Product { productID=3, productName="Prod5", productPrice=30.00, stockQuantity= 120 },
new Product { productID=4, productName="Prod6", productPrice=19.50, stockQuantity= 30 },

};

Console.WriteLine("\nTake While price < 99\n");

// prints nothing since 'prodA' start with price = '100.50'
var v = prodA.TakeWhile(a => a.productPrice < 99);

// This will print the 4 rows where the price is less than 99.
// Ordered + TakeWhile = Where

var u = prodA.OrderBy(a=>a.productPrice).TakeWhile(a => a.productPrice < 99);

foreach (var v1 in u)
{
Console.WriteLine("ProdId:{0}, ProdName:{1}, Price:{2}, Qty:{3}",
v1.productID, v1.productName, v1.productPrice, v1.stockQuantity );
}

}


OUTPUT :

Take While price < 99

ProdId:4, ProdName:Prod6, Price:19.5, Qty:30
ProdId:3, ProdName:Prod5, Price:30, Qty:120
ProdId:3, ProdName:Prod3, Price:51, Qty:120
ProdId:4, ProdName:Prod4, Price:79.5, Qty:30