Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Thursday, May 6, 2010

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

Monday, April 26, 2010

LINQ Samples (Projection Operators) : Select Indexed

In this example we explore the index for a given enumeration. In the statement
var str = strTech.Select( (a, b) => new { condition = a.Length > b , strTech = a });


a is the object strTech , b in the index or position of enumeration, new {} is the anonymous type.


private void SelectIndexed()
{
int[] num = { 1,2,3,4,5,6,7,8,9};
string[] strTech = new string[] { "C#", "asp.net", "vb.net", "j#", "f#", "Cobol.net", "LINQ", "WCF", "WPF", "Silverlight" };

var str = strTech.Select( (a, b) => new { condition = a.Length > b , strTech = a });

foreach (var s in str)
{
Console.WriteLine("{0}\t{1}", s.strTech, s.condition);
}
}


OUTPUT

C# True
asp.net True
vb.net True
j# False
f# False
Cobol.net True
LINQ False
WCF False
WPF False
Silverlight True

LINQ Samples (Projection Operators) : Select Anonymous

Following example is used with Anonymous type for a select operation.It provides an transformed output as a Anonymous type


private void SelectAnonymousTypeOne()
{
string[] strTech = new string[] { "C#", "asp.net", "vb.net", "j#", "f#", "Cobol.net", "LINQ", "WCF", "WPF", "Silverlight" };

var str = strTech.Select(a =>
new { str = a.ToString(),
length = a.Length ,
specialChar = a.EndsWith("#")
});

foreach(var v in str)
{
Console.WriteLine("{0}\n Length:{1} Ends With #{2}",v.str,v.length , v.specialChar );

}
}

OUTPUT

C#
Length:2 Ends with char '#': True
asp.net
Length:7 Ends with char '#': False
vb.net
Length:6 Ends with char '#': False
j#
Length:2 Ends with char '#': True
f#
Length:2 Ends with char '#': True
Cobol.net
Length:9 Ends with char '#': False
LINQ
Length:4 Ends with char '#': False
WCF
Length:3 Ends with char '#': False
WPF
Length:3 Ends with char '#': False
Silverlight
Length:11 Ends with char '#': False

LINQ Samples (Projection Operators) : Select Transformation

Following example will obtain the odd string from there index position based on the value from a different array. If this is to be acheived by for loop; two for loops are required.


private void SimpleSelectTransformation()
{
int[] num = { 1, 3, 5, 7, 9};

string[] strTechn = new string[] { "C#", "asp.net", "vb.net", "j#", "f#", "Cobol.net", "LINQ", "WCF", "WPF", "Silverlight" };
var trans1 = num.Select(a => strTechn[a]);

foreach (string s in trans1)
{
Console.WriteLine(s);
}
}


OUTPUT:

asp.net
j#
Cobol.net
WCF
Silverlight

LINQ Samples (Projection Operators) : Example 2

Following example is used to obtain all product name from a list of 'Product'.

In the statement var v = prod.Select(a => a.productName); a is nothing but a placeholder or act as a parameter that represent object 'prod'.


private void SimpleSelectTwo()
{

List prod = new List
{
new Product() { productID=1, productName="Cooking Oil", productPrice=21.5, stockQuantity=10 },
new Product() { productID=2, productName="Washing Powder", productPrice=38, stockQuantity=10 },
new Product() { productID=3, productName="Tea bags", productPrice=110, stockQuantity=100 },
new Product() { productID=4, productName="Garbase bags", productPrice=21.5, stockQuantity=12 },
new Product() { productID=5, productName="Health drink", productPrice=85, stockQuantity=18 },
new Product() { productID=6, productName="Cool drinks", productPrice=45, stockQuantity=15 }
};
Console.WriteLine("\nBefore LINQ :");
foreach (Product pr in prod)
{
Console.WriteLine("ProdId: {0}, ProdName: {1}, ProdPrice: {2}, Stock: {3} ", pr.productID, pr.productName,pr.productPrice, pr.stockQuantity );
}

var v = prod.Select(a => a.productName);

Console.WriteLine("\nAfter LINQ : only Product is selected");
foreach(string pr in v )
{
Console.WriteLine("Product Name : {0}", pr);
}

}

OUTPUT

Before LINQ :
ProdId: 1, ProdName: Cooking Oil, ProdPrice: 21.5, Stock: 10
ProdId: 2, ProdName: Washing Powder, ProdPrice: 38, Stock: 10
ProdId: 3, ProdName: Tea bags, ProdPrice: 110, Stock: 100
ProdId: 4, ProdName: Garbase bags, ProdPrice: 21.5, Stock: 12
ProdId: 5, ProdName: Health drink, ProdPrice: 85, Stock: 18
ProdId: 6, ProdName: Cool drinks, ProdPrice: 45, Stock: 15

After LINQ : only Product name is selected
Product Name : Cooking Oil
Product Name : Washing Powder
Product Name : Tea bags
Product Name : Garbase bags
Product Name : Health drink
Product Name : Cool drinks

Sunday, April 25, 2010

LINQ Sample using lambda Expressions

The LINQ Samples are modification for the existing examples at 'http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx'.

The example here serve two purpose one is all are using lambda expression instead of the query used such that whoever is from a lambda expression background can understand those examples and secondly its more details for beginners.

Restriction Operators
Simple where 1
Simple where 2
Simple where 3
Simple where drill down
Simple where using indexed

Projection Operators
Simple select example 1
Simple select example 2
Select transformation
Select anonymous type example1
Select indexed
Select filtered
Select Compound 1 (combine two unrelated list)
Select Compound 2 (combine two unrelated list)

Partitioning Operators
Take simple and nested
Skip simple and nested
TakeWhile simple
SkipWhile simple
Take and Skip combined

LINQ Samples (Projection Operators) : Example 1

Example 1 : Provide a simple select which will allow to do a select on the list of string with a simple modification

private void SimpleSelectOne()
{
Console.WriteLine("Simple Select operations \n");
string[] strTechnology = new string[] { "C#","asp.net","vb.net","j#","f#","Cobol.net","LINQ","WCF","WPF","Silverlight" };

Console.WriteLine("\nBefore LINQ :");
foreach (string s in strTechnology)
{
Console.WriteLine("{0}", s);
}

Console.WriteLine("\nAfter LINQ transform : ");
var strList = strTechnology.Select( a => "MS " + a );
foreach (string s in strList)
{
Console.WriteLine("{0}",s);
}
}


OUTPUT :

BEFORE LINQ :
C#
asp.net
vb.net
j#
f#
Cobol.net
LINQ
WCF
WPF
Silverlight

AFTER LINQ transform :
MS C#
MS asp.net
MS vb.net
MS j#
MS f#
MS Cobol.net
MS LINQ
MS WCF
MS WPF
MS Silverlight


You can see that the statement var strList = strTechnology.Select( a => "MS " + a ); has added a string "MS" to existing string. Let it be reminded that the original string remains the same.