Friday, May 7, 2010

LINQ lambda Samples (Partitioning operator) : 'SkipWhile' example

'SkipWhile' is similar to takewhile except that skipwhile will take the values from list until the condition is met.

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

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

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

Console.WriteLine("\n\nPrint num (ordered) with SkipWhile until value is not > 150 ");
IEnumerable i2 = num.OrderBy(a => a).SkipWhile(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 SkipWhile until value is not > 150
223 442 4 61 40

Print num (ordered) with SkipWhile until value is not > 150
223 442

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

LINQ lambda Samples (Partitioning operator) : 'Skip' simple and Nested

Example Simple: Skip is the opposite of 'Take', where it skips the values in a collection until numeric value specified. Following simple example shows the usage if 'skip' which skips first'5' values.

public void SkipSimple()
{
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 with Skip(5) ");
IEnumerable i = num.Skip(5);

foreach (int j in i)
{
Console.Write("{0} ", j);
}
}

OUTPUT :
Print num
34 56 72 74 223 442 4 61 40

Print num with Skip(5)
442 4 61 40

Example Nested : Consider the following example which first filters the collection and then apply 'Skip' to it.

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

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

Console.WriteLine("\n\nPrint num where value > 25");
IEnumerable i1 = num.Where(a => a > 25);
foreach (int j in i1)
Console.Write("{0} ", j);

Console.WriteLine("\n\nPrint num where value > 25 and skip 5");
IEnumerable i2 = num.Where(a => a > 25).Skip(5);
foreach (int j in i2)
Console.Write("{0} ", j);
}

OUTPUT :
Print num
34 36 56 72 45 74 223 442 4 61 40

Print num where value > 25
34 36 56 72 45 74 223 442 61 40

Print num where value > 25 and skip 5
74 223 442 61 40

Monday, May 3, 2010

LINQ Samples (Partitioning operator) : 'Take' simple and Nested

Example simple : Example takes the first 5 values from the collection using the 'Take' operator


public void TakeSimple()
{
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 with take(5) ");
IEnumerable i = num.Take(5);

foreach (int j in i)
{
Console.Write("{0} ",j);
}
}


OUTPUT :

Print num
34 56 72 74 223 442 4 61 40

Print num with take(5)
34 56 72 74 223



Example Nested : Following example first check a condition using restriction operator 'where', then applies 'Take' to the result


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

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

Console.WriteLine("\n\nPrint num where value > 25");
IEnumerable i1 = num.Where(a => a > 25);
foreach (int j in i1)
Console.Write("{0} ", j);

Console.WriteLine("\n\nPrint num where value > 25 and take only 5");
IEnumerable i2 = num.Where(a => a > 25).Take(5);
foreach (int j in i2)
Console.Write("{0} ", j);
}


OUTPUT :

Print num
34 36 56 72 45 74 223 442 4 61 40

Print num where value > 25
34 36 56 72 45 74 223 442 61 40

Print num where value > 25 and take only 5
34 36 56 72 45

LINQ Samples (Projection Operators) : Select Compound 2

Following example uses LINQ lambda on a 2 set of objects. Eventhough join is used here the condition is set to 'true', simply to join the collection.

Also note the 'query' equivalent of the lambda code as commented out section .(Eventhough the query expression is easier to write, this examples are all in lambda expression of people who are interested in lambdas)


private void SelectManyCompound()
{
List prodA = new List {
new Product { productID=1, productName="Prod1", productPrice=100.50, stockQuantity= 10 },
new Product { productID=2, productName="Prod2", productPrice=89.50, stockQuantity= 15 },
new Product { productID=3, productName="Prod3", productPrice=10.00, stockQuantity= 120 },
new Product { productID=4, productName="Prod4", productPrice=19.50, stockQuantity= 30 },

};

List orderA = new List {

new Order { CustomerName="Ben", OrderNo=1, TotalAmt= 1000},
new Order { CustomerName="Alice", OrderNo=2, TotalAmt= 900},
new Order { CustomerName="Sam", OrderNo=3, TotalAmt= 700},
};

var v = prodA.Join(orderA, a => true, b => true,
(a, b) =>
new
{
Prod = a,
order = b
})
.Where( (c) => c.Prod.productPrice > 75 );

/* Equivalent code using Query
var v = from a in prodA
from b in orderA
where a.productPrice > 75
select new { Prod = a, order = b };
*/

foreach (var v1 in v)
{
Console.WriteLine("ProdId:{0}, ProdName:{1}, Price:{2}, Qty:{3}, CustNm:{4}, OrdNo:{5},Total:{6}",
v1.Prod.productID,v1.Prod.productName,v1.Prod.productPrice,v1.Prod.stockQuantity,
v1.order.CustomerName,v1.order.OrderNo,v1.order.TotalAmt
);
}
}


OUTPUT

ProdId:1, ProdName:Prod1, Price:100.5, Qty:10, CustNm:Ben, OrdNo:1,Total:1000
ProdId:1, ProdName:Prod1, Price:100.5, Qty:10, CustNm:Alice, OrdNo:2,Total:900
ProdId:1, ProdName:Prod1, Price:100.5, Qty:10, CustNm:Sam, OrdNo:3,Total:700
ProdId:2, ProdName:Prod2, Price:89.5, Qty:15, CustNm:Ben, OrdNo:1,Total:1000
ProdId:2, ProdName:Prod2, Price:89.5, Qty:15, CustNm:Alice, OrdNo:2,Total:900
ProdId:2, ProdName:Prod2, Price:89.5, Qty:15, CustNm:Sam, OrdNo:3,Total:700

LINQ Samples (Projection Operators) : Select Compound

Following example is using select on 2 set of collections.The example is equivalent to the query

var v = from a in numA
from b in numB
where a < b
select new { a = a,b = b};


private void SelectMany()
{
List numA = new List { 12, 25, 5, 6, 7, 28, 9 };
List numB = new List { 11, 22, 15, 16, 27 };

var v = numA.Join(numB, a => true, b => true,
(a, b) => new { a= a, b=b }).Where(c=>c.a < c.b );

foreach (var v1 in v)
{
Console.WriteLine("{0}",v1 );
}
}


OUTPUT

{ a = 12, b = 22 }
{ a = 12, b = 15 }
{ a = 12, b = 16 }
{ a = 12, b = 27 }
{ a = 25, b = 27 }
{ a = 5, b = 11 }
{ a = 5, b = 22 }
{ a = 5, b = 15 }
{ a = 5, b = 16 }
{ a = 5, b = 27 }
{ a = 6, b = 11 }
{ a = 6, b = 22 }
{ a = 6, b = 15 }
{ a = 6, b = 16 }
{ a = 6, b = 27 }
{ a = 7, b = 11 }
{ a = 7, b = 22 }
{ a = 7, b = 15 }
{ a = 7, b = 16 }
{ a = 7, b = 27 }

Sunday, May 2, 2010

LINQ Samples (Projection Operators) : Select Filtered

In following example we see how to filter the using the 'where' clause. Example will produce the list of students that have roll numbers less than 10. Roll number is in int variable 'rollnum' and student's name are in string variable 'Studname'.

See how first we need to fetch the element and the corresponding positions such that we can fetch the proper name from studname'



private void SelectFiltered()
{
int[] Rollnum = { 6, 8, 2, 4, 12, 11, 7, 1, };
string[] StudName = { "Betty", "Helen", "Alice", "Ben", "Zen", "Jim", "Davan", "Alan" };

var roll = Rollnum
// get the Element,index
.Select( (a,b) => new
{
rollnum = a ,
index = b
})
// get the Rollnum which are < 10
.Where((a) => a.rollnum < 10)
// get the studname corresponding to the Rollnum index
.Select((a)=> new
{
stud = StudName[a.index]
})
//Order based on name
.OrderBy(c=>c.stud);

Console.WriteLine("Student with Roll num < 10");
foreach (var s in roll)
{
Console.WriteLine("{0}", s.stud);
}
}


OUTPUT

Student with Roll num < 10
Alan
Alice
Ben
Betty
Davan
Helen

Saturday, May 1, 2010

LINQ Samples (Restriction operator) : Select simple 1

A simple where clause used to find all elements that are greater than value 'x'

private void LINQWhereOne()
{
//Find Array where elements are less than x;
int x = 25;

int[] numeric = new int[] { 12, 18, 35, 50, 24, 25, 10, 15, 18 };
var lessThanX = numeric.Where(a => a < x);

Console.WriteLine("Array where elements are less than {0}",x);
foreach(int i in lessThanX )
{
Console.WriteLine("{0}",i);
}
}

OUTPUT :

Array where elements are less than 25
12
18
24
10
15
18


LINQ Samples (Restriction Operators) : Select simple 2
Going forward with 'Where' another simple example that works with Object

private void LINQWhereTwo()
{
//Find product where stock is 0
var noStock = prod.Where(a => a.Stock <= 0);

Console.WriteLine("Product where stock is 0");
foreach (Product pd in noStock)
{
Console.WriteLine("ProductId : {0} ,ProductName : {1} , ProductPrice : {2} , Stock : {3}",
pd.ProductId, pd.ProductName, pd.ProductPrice, pd.Stock );
}
}

OUTPUT :

Product where stock is 0
ProductId : 5 ,ProductName : Noodles , ProductPrice : 25.4 , Stock : 0
ProductId : 6 ,ProductName : Washing Powder , ProductPrice : 25.4 , Stock : 0