Monday, 21 April 2008

LINQ (Language INtegrated Query)

LINQ is a very powerful feature brought to us by Microsoft in .net 3.0 or rather c# 3.0. When I first time knew about LINQ my understanding was that “Microsoft is trying to replace SQL with LINQ” but I was wrong. Here I will cover some basics of LINQ and few jargons which skirt around LINQ.

1. Till now we were able to query the tables but LINQ allows us to query Collection which has really made our life easier as well as it brings better understanding of the code.
For eg.

If you have a collection of products and your products are categorized into let’s say Electronic/Apparel/Toys etc.

Now let’s consider you want to retrieve one of the specific category product.

Now to achieve above task, probably we have to iterate through entire product collection then we have to out a check for our specific category and then we need to add it into our new collection.

Something similar to following code snippet.

List<Products> Toys = new List<Products>();
foreach (Product p in Products)
if (p.TYpe == "Toys")
Toys.Add(p);

Now you can achieve above task in much easier way something like..

var Toys = from p in Products
where p.Type == "Toys"
select new {p.ID,p.name,p.cost,p.qty};

2. Till now, using the conventional methods we were just writing a lots of code for few task related with collection, now this can be reduced extensively using Lambda and Extension methods

public int GetSalesByAreaCode(int AreaCode)
{
int totalSales = 0;

foreach (Sale saleItem in this.Sales)
{
if (saleItem.AreaCode == AreaCode)
{
totalSales++;
}
}

return totalSales;
}
But if you are aware of LINQ's Lambda and Extention method you can achive above task in few lines of code.


public int GetSalesByAreaCode(int AreaCode)
{
return this.Sales.Count(saleItem => saleItem.AreaCode == AreaCode);
}

If you add a reference of System.Linq then following method is automatically added in all the arrays,generic list or any of the "IEnumerable" class.

Any
Average
Count
Where
OrderBy

above functions are pretty much like our SQL functions.

I hope, It would have given you enough curiosity to read up about LINQ

No comments:

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...