LINQ FAQ Part 1

No.of Views806
Bookmarked0 times
Downloads 
Votes0
By  questpond   On  16 Feb 2010 00:02:29
Tag : LINQ , How to
LINQ FAQ Part 1
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

LINQ FAQ Part 1

Introduction and Goal

Define LINQ?

How does LINQ help us from the perspective of business objects?

Can you explain how a basic LINQ Query looks like?

How do we write a LINQ query to search with criteria?

How can do a join using LINQ query?

How can we do a group by using LINQ query?

How can we do an order by using LINQ query?

Source Code

Introduction and Goal

In this section we will run through basics of LINQ and then see 5 basic LINQ queries which you will always need in your project for queries. While looking at the basics we will also try to learn what problem LINQ solves from the perspective of middle tier business objects.

You can download my 1000 Questions and answers .NET book from the below link , I am dead sure you will enjoy it.

http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip

Define LINQ?

LINQ is a uniform programming model for any kind of data access. LINQ enables you to query and manipulate data independently of data sources. Below figure 'LINQ' shows how .NET language stands over LINQ programming model and works in a uniformed manner over any kind of data source. It’s like a query language which can query any data source and any transform. LINQ also provides full type safety and compile time checking.
LINQ can serve as a good entity for middle tier. So it will sit in between the UI and data access layer.

Figure - LINQ

Below is a simple sample of LINQ. We have a collection of data ‘objcountries’ to which LINQ will is making a query with country name ‘India’. The collection ‘objcountries’ can be any data source dataset, datareader, XML etc. Below figure ‘LINQ code snippet’ shows how the ‘ObjCountries’ can be any can of data. We then query for the ‘CountryCode’ and loop through the same.

Figure: - LINQ code snippet


How does LINQ help us from the perspective of business objects?

One of the tedious jobs in business object is parsing and searching object collections. For instance consider the below figure where we want to search a country by an ‘ID’ value. So what we do is loop through the collection and get the object. Many may argue how about keeping a key in List or Array. The below example is just a sample. For instance if you want to search using country code and name, list / collection keys will not work with those multi-value searches.

In other words using LINQ we can query business object collections and filter the collection in a single LINQ query.

Can you explain how a basic LINQ Query looks like?

In order to understand the basic query for LINQ, let’s make a small sample project. Let’s take customer data which has customer and orders.

Customer NameCustomer CodeCityOrders
Khadak001Mumbai
  • Shirts
  • Socks
Shiv002Delhi
  • Pants
Raju003Mumbai
  • Socks
Shaam004Delhi
  • Shoes

We have made the data a bit complex by have one customer and multiple orders , in other words we have one as to many relationship.

So let’s make two classes one is the customer class aggregated with a collection of addresses class. Below is how the class structure will look like to accommodate the one as to many relationships of customer and multiple addresses.

The multiple addresses are the array collection aggregated inside the customer class. So below is the code snippet which is loading the customer and address collections with hard coded data provided in the above table. Currently its hardcoded but this can be loaded from database or some other source also.

clsCustomer[] objCustomer = new clsCustomer[]
{
new clsCustomer{CustomerName="Khadak",customerCode="001",City="Mumbai",Orders = new clsOrder[]
{new clsOrder{ProductName="Shirt"},
new clsOrder{ProductName="Socks"}}},
new clsCustomer{CustomerName="Shiv",customerCode="002",City="Delhi",Orders = new clsOrder[]{new clsOrder{ProductName="Pants"}}},
new clsCustomer{CustomerName="Raju",customerCode="003",City="Mumbai",Orders = new clsOrder[]{new clsOrder{ProductName="Socks"}}},
new clsCustomer{CustomerName="Shaam",customerCode="004",City="Delhi",Orders = new clsOrder[]{new clsOrder{ProductName="Shoes"}}}};

A basic LINQ query looks like something as shown below. Its start with the verb from followed by the data type and object i.e. ‘clsCustomer’ and ‘obj’ object. ‘objCustomer’ is the collection which has customer and addresses which we have loaded in the top section. ‘select obj’ specifies that we need all the values.

from clsCustomer obj in objCustomer select obj

Below figure shows in the right hand side the query in LINQ. In the left hand side we loop through the object collection.



We have made a simple project which demonstrates the basic LINQ query; you can download the same see how it works actually. Below figure shows the execution of the simple query.

How do we write a LINQ query to search with criteria?

We need to put the where clause before the ‘select’ keyword.

return from clsCustomer Obj in objCustomer where Obj.customerCode == “001” select Obj;

Below figure shows the where clause in action.

How can do a join using LINQ query?

Below is the LINQ code snippet for creating joins between object collections. In this case we are creating a join on customer and orders. If you remember the order collection was contained in the customer class.

return from clsCustomer ObjCust in objCustomer 
from clsOrder ObjOrder in ObjCust.Orders
select ObjCust;

Below is the result of how LINQ join query looks like.

How can we do a group by using LINQ query?

Below is the code snippet which shows how group by query is written using LINQ. You can see we have created first a temp variable i.e. ‘GroupTemp’ and then we have used the ‘Select’ clause to return the same.

var GroupCustomers = from ObjCust in objCustomer
group ObjCust by ObjCust.City into GroupTemp
select new {GroupTemp.Key,GroupTemp};

Below image shows group by in action.

How can we do an order by using LINQ query?

Order by in LINQ is pretty simple. We just need to insert order by before the ‘Select’ query.

return from clsCustomer ObjCust in objCustomer
orderby ObjCust.City
select ObjCust;

Below figure shows how we have ordered on the city name.

Source Code

You can get the code snippet of the above LINQ queries from Click here

Thank you

Shivprasad Koirala

 
Sign Up to vote for this article
 
About Author
 
questpond
Occupation-
Company-
Member Type-Expert
Location-Not Provided
Joined date-24 Jun 2009
Home Page-
Blog Page-
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top