Click here to Skip to main content
13,196,730 members (71,430 online)
Click here to Skip to main content
Add your own
alternative version


33 bookmarked
Posted 8 Sep 2008

Better LINQ with better example

, 8 Sep 2008
Rate this:
Please Sign up or sign in to vote.
Here we will take a real time example of a company to explore LINQ


What is LINQ??

LINQ stand for Language-Integrated Query is now available as a integral part of Visual Studio 2008.

LINQ has a great power of querying on any source of data, data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and that are give below.

  • LINQ to Object
  • LINQ to ADO.Net  
    • LINQ to SQL
    • LINQ to Dataset
    • LINQ to Entities
  • LINQ to XML


Basics samples of LINQ (for beginners) :

Assuming you know the basics of LINQ I will continue with a bit high end sample lets move further with an example of a company.



The Company sample: 

  • Downloads: 

Here we will see how a linq can be utilized in a company module.

The company class will contain a Collection of employee class and employee will contain a struct for individual addresses.





If we have a project with above hierarchy, let’s see how we can use LINQ to access details from multilevel classes.


After creation of companies we will try to find the details at multilevel and see how conditionally data can be fetched.

1)      List details of employees

2)      Count no of employees in each company

3)      List employees who are staying in <st1:place w:st="on"><st1:city w:st="on">Bangalore

4)      List employee who is paid highest in each companies

5)      Overall Highest paid employee

6)      Salary paid by companies in each city

7)      Salary paid by each company in each city.


List details of employees:

Now we shall list all the employees with their details and company name.

var EmpDetails = from comp in ListCompany 
                 select new<o:p> {
                       Emp = (from emp in comp.ListEmp<o:p>  
                              select new {
                                   Company = comp.Name, 
                  }; </o:p></o:p>

Here we use sub queries since we need all employee details with their respective company name and both the details are at different levels.

So first we Loops through the companies in the company list  

from comp in ListCompany  

and then within each selected company it loops through each employee <o:p>

from emp in comp.ListEmp 


Count no of employees in each company:<o:p>

[__strong__]<o:p> </o:p> var LessEmp = from  Comp in  ListCompany  
                select new<o:p> { 
                       EmpCount = Comp.ListEmp.Count
                            };   </o:p>

List employees who are staying in <st1:city w:st="on"><st1:place w:st="on">Bangalore: 

Here we use compound from clause to retrieve the employees who are staying in any city that contains BAN or ban.  

var EmpInACity = from comp in ListCompany<o:p> 

                 from emplist in comp.ListEmp 
                 where emplist.Address.City.ToUpper().Contains(&quot;BAN&quot;)
                 select new {
                        CompName = comp.Name,
                        EmployeeName = emplist.Name 
                 }; </o:p>

List employee who is paid highest in each companies: 

For finding the highest paid employee we first loop through all the companies and employees in each company using compound from clause.

Where condition filters only those employees those have the salary equal to the max salary in current company. 

var  EmpHighSalEachComp = from comp in ListCompany 
                          from empHigh in comp.ListEmp  
                          where empHigh.salary == comp.ListEmp.Max(
                          HighEmp => HighEmp.salary)<o:p> 
                          select new {
                                 CompanyName = comp.Name, 
                                 EmpHighName = empHigh.Name,
                                 EmpHighSal = empHigh.salary
                          }; </o:p>

Overall Highest paid employee:

The same above procedure is followed but the only difference comes in the where condition where we match the employee’s salary to the max salary from all the companies. 

var EmpHighSal = from comp in ListCompany
                 from emp in comp.ListEmp 
                 where emp.salary == ListCompany.Max(
                 TComp => TComp.ListEmp.Max(HighEmp => HighEmp.salary))
                 select new {
                        CompanyName = comp.Name ,
                        EmployeeName = emp.Name,
                        EmpSal = emp.salary

Salary paid by companies in each city: 

Here we will group by city and sum up all the salaries of the employees who are staying in that city. 

var CompanyCityWise = from comp in ListCompany          

                      from emp in comp.ListEmp 
                                       group emp by emp.Address.City into CityWiseEmp 
                      select new {
                             State = CityWiseEmp.Key, 
                             TotalSalary = CityWiseEmp.Sum(emp => emp.salary) 

Salary paid by each company in each city. 

Here for each company a group by clause is applied and from each company employees staying at different locations are fetched.

var  CityWiseSalary = from comp in ListCompany 
                      select new { 
                             Emp =(from emp in comp.ListEmp 
                             group emp by emp.Address.City into CityWiseEmp
                             select new {
                                    State = CityWiseEmp.Key,
                                    TotalSalary = CityWiseEmp.Sum(emp => emp.salary) 

More references on LINQ:

More samples on LINQ: 

In Depth LINQ: (Naveen's Weblog)

Standard Query Operators in a Nutshell:

More LINQ:

Any suggestions are most welcome.

Happy learning :) 



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


About the Author

Software Developer (Senior) Relyon Softech LTD, Bangalore.
India India
I m a software Engineer working on .Net and SQL Server 2005.

You may also be interested in...


Comments and Discussions

AnswerMy Vote of 5 Pin
Snesh124-Oct-13 20:35
memberSnesh124-Oct-13 20:35 
GeneralMy vote of 4 Pin
crcklssp3-Mar-13 18:30
membercrcklssp3-Mar-13 18:30 
QuestionThis is very good article. Pin
Jayesh Sorathia6-Dec-12 21:13
memberJayesh Sorathia6-Dec-12 21:13 
This is very good article.
For more real life example of linq that are use in day to day life of software development visit this blog.
Visit This blog. Click Here...
GeneralMy vote of 5 Pin
srinivaskumar pasumarthi3-Nov-12 0:24
membersrinivaskumar pasumarthi3-Nov-12 0:24 
QuestionI am unable to unzip the zip code file Pin
Rukeshjee12-Sep-12 7:13
memberRukeshjee12-Sep-12 7:13 
GeneralMy vote of 5 Pin
prabhakamaji30-Nov-11 1:08
memberprabhakamaji30-Nov-11 1:08 
GeneralMy vote of 5 Pin
Member 7143808-Sep-10 1:47
memberMember 7143808-Sep-10 1:47 
GeneralMy vote of 1 Pin
cupim1-Feb-10 6:57
membercupim1-Feb-10 6:57 
GeneralNice article Pin
ankurpatell8-Sep-09 8:01
memberankurpatell8-Sep-09 8:01 
GeneralGood one.... Pin
manas17-Sep-08 3:39
membermanas17-Sep-08 3:39 
GeneralRe: Good one.... Pin
NaveenPrabhu18-Sep-08 1:48
memberNaveenPrabhu18-Sep-08 1:48 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171019.1 | Last Updated 9 Sep 2008
Article Copyright 2008 by NaveenPrabhu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid