Labels

Tuesday, April 29, 2008

LINQ - Shaping Query Results

Hi,

This blog post summarizes the overview of LINQ.

Below are the new features been introduced in Orcas

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extesnion Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

§ Var Keyword

These language features help in making query against relational data. This overall querying programming model is called as "LINQ" - which stands for .NET Language Integrated Query.

Shaping Query Results

Shaping – Retrieving Subset of Data.

Below is the LINQ code is used to extract the product details

private void QueryProduct()

{

NorthwindDataContext db = new NorthwindDataContext();

var products = from p in db.MyProducts

where p.Category.CategoryName == "Beverages"

select p;

}

Often we only want to return a subset of the data. This is called as Data Shaping Features that LINQ and the new C# and VB compilers supports. Below is the example.

NorthwindDataContext db = new NorthwindDataContext();

var products = from p in db.MyProducts

select new

{

ID = p.ProductID,

Name = p.ProductName

};

Using Built-in System.Linq Extension Methods:

In Shaping query results, the ‘Built-in System.Linq Extension Methods’ can be used to take the full advantage of data model class associations to generate the complex shaped results.

NorthwindDataContext db = new NorthwindDataContext();

var products = from p in db.MyProducts

select new

{

ID = p.ProductID,

Name = p.ProductName,

NumOrders = p.Order_Details.Count,

Revenue = p.Order_Details.Sum(o => o.Quantity * o.UnitPrice)

};

Reference: http://weblogs.asp.net/scottgu/archive/2007/06/29/linq-to-sql-part-3-querying-our-database.aspx

Hope this helps.

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment