Click here to Skip to main content
14,867,295 members
Articles / Programming Languages / C#
Posted 4 Mar 2009

Tagged as


202 bookmarked

LINQ FAQ for Newbies

Rate me:
Please Sign up or sign in to vote.
4.80/5 (55 votes)
17 Jul 2009CPOL5 min read
Frequency asked questions for LINQ newbies
This is an article for beginners in LINQ and provides answers to frequently asked questions.


Introduction and Goal

In this section, we will run through the basics of LINQ and then see five 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 problems LINQ solves from the perspective of middle tier business objects.

You can download my 1000 questions and answers .NET book. I am dead sure you will enjoy it.


LINQ FAQ Part II: In this FAQ, we will see a basic example of LINQ to SQL, how to define 1-1 and 1-many relationships using LINQ, how we can optimize LINQ queries, execution of Stored Procedures using LINQ, and finally a simple CRUD example using LINQ to SQL.

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. The figure below shows how .NET languages stand over the LINQ programming model and work in a uniform 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 the middle tier. So it will sit in between the UI and data access layers.

Image 1

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

Image 2

How does LINQ Help Us from the Perspective of Business Objects?

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

Image 3

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

Can You Explain How a Basic LINQ Query Looks Like?

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

Customer Name Customer Code City Orders
Khadak 001 Mumbai
  • Shirts
  • Socks
Shiv 002 Delhi
  • Pants
Raju 003 Mumbai
  • Socks
Shaam 004 Delhi
  • Shoes

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

Image 4

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

Image 5

The multiple addresses are the array collection aggregated inside the customer class. Shown below is a code snippet which loads the customer and address collections with hard coded data provided in the above table. Currently it is hardcoded, but this can be loaded from a 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. It starts with the verb from followed by the data type and the objects, i.e., clsCustomer and obj objects. objCustomer is the collection which has the 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

The figure below shows on the right hand side the query in LINQ. In the left hand side, we loop through the object collection.

Image 6

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

Image 7

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;

The figure below shows the where clause in action.

Image 8

How to Do a Join Using LINQ Query

Below is a 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;

Shown below is the result of a LINQ join query:

Image 9

How Can We Do a Group by Using LINQ Query?

The code snippet below shows how a group by query is written using LINQ. You can see we have first created a temp variable GroupTemp and then used the Select clause to return it.

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

The image below shows group by in action.

Image 10

How Can We Do an Order by Using a 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;

The figure below shows how we have ordered on the city name.

Image 11


  • 5th March, 2009: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Comments and Discussions

SuggestionMy vote of 5 Pin
The14thNoah15-May-14 23:03
MemberThe14thNoah15-May-14 23:03 
QuestionMy Vote of 4 Pin
Rahul VB5-May-14 21:45
professionalRahul VB5-May-14 21:45 
GeneralMy vote of 4 Pin
Armando de la Torre26-Jun-12 8:49
MemberArmando de la Torre26-Jun-12 8:49 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey8-Jun-12 10:01
professionalManoj Kumar Choubey8-Jun-12 10:01 
Suggestionwhat about complicated quires Pin
eiaddar17-May-12 21:35
Membereiaddar17-May-12 21:35 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey16-May-12 18:25
professionalManoj Kumar Choubey16-May-12 18:25 
QuestionMy vote of 5 Pin
ramesh_nrk6-Apr-12 2:38
Memberramesh_nrk6-Apr-12 2:38 
GeneralMy vote of 5 Pin
ramesh_nrk6-Apr-12 2:37
Memberramesh_nrk6-Apr-12 2:37 
GeneralMy vote of 4 Pin
Itz.Irshad13-Feb-12 17:44
MemberItz.Irshad13-Feb-12 17:44 
GeneralMy vote of 5 Pin
Raj Champaneriya16-Dec-11 15:24
professionalRaj Champaneriya16-Dec-11 15:24 
GeneralMy vote of 5 Pin
Sandesh M Patil17-Jun-11 1:09
MemberSandesh M Patil17-Jun-11 1:09 
GeneralMy vote of 2 Pin
BSRK17-May-11 19:49
MemberBSRK17-May-11 19:49 
GeneralRe: My vote of 2 Pin
RyanEK24-Aug-11 12:33
MemberRyanEK24-Aug-11 12:33 
GeneralMy vote of 4 Pin
Amir Mehrabi-Jorshari20-Oct-10 1:43
MemberAmir Mehrabi-Jorshari20-Oct-10 1:43 
GeneralMy vote of 5 Pin
irfan patel14-Jul-10 11:04
Memberirfan patel14-Jul-10 11:04 
General5 STARS Pin
irfan patel14-Jul-10 10:07
Memberirfan patel14-Jul-10 10:07 
GeneralApostrophes (check title) Pin
tec-goblin11-Mar-09 4:03
Membertec-goblin11-Mar-09 4:03 
GeneralLINQ to Word/Excel Pin
Qistoph4-Mar-09 23:38
MemberQistoph4-Mar-09 23:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.