Click here to Skip to main content
15,886,578 members
Articles / Web Development / HTML

A Very Simple LINQ Example

Rate me:
Please Sign up or sign in to vote.
3.40/5 (11 votes)
16 Sep 2014CPOL2 min read 46.1K   673   12   10
This is a very simple but practical implementation of LINQ.

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Introduction

There are far too many good and very useful articles on the web as well as on CodeProject about LINQ. So I do not claim that this article demonstrates something extraordinary or something which has not been attempted before. But I find LINQ so interesting that I wanted to share something about LINQ which I have myself implemented and can help those who want to learn LINQ.

In this article, I am showing the use of LINQ in displaying, sorting, grouping and filtering data.

Background

LINQ can be used to perform query operations on a variety of data sources such as databases, arrays, lists, XML files, etc. In this article, I am extracting the data stored in an array. The data is about 10 most populous countries of the world. There is a class called Countries, having attributes country, population and continent. An array of the Countries class is used to hold data about the 10 most populous countries of the world. This data is extracted using LINQ and bound to a GridView object.

Note: For the purpose of grouping, I have specified the continent for United States and Brazil as America, instead of North America and South America.

Using the Code

Following is the code of the Countries class:

C#
public class Countries
{
    public string Country
    {
        get;
        set;
    }
    public long Population
    {
        get;
        set;
    }
    public string Continent
    {
        get;
        set;
    }
}

The following is the Page_Load event handler, which stores the countries information in an array of the Countries class:

C#
protected void Page_Load(object sender, EventArgs e)
{
    for (int ctr = 0; ctr < cc.Length;ctr++ )
    {
        cc[ctr] = new Countries();
    }
    cc[0].Country = "Bangladesh";
    cc[0].Population = 156594962;
    cc[0].Continent = "Asia";
    cc[1].Country = "Brazil";
    cc[1].Population = 200361925;
    cc[1].Continent = "America";
    cc[2].Country = "China";
    cc[2].Population = 1357380000;
    cc[2].Continent = "Asia";
    cc[3].Country = "India";
    cc[3].Population = 1252139596;
    cc[3].Continent = "Asia";
    cc[4].Country = "Indonesia";
    cc[4].Population = 249865631;
    cc[4].Continent = "Asia";
    cc[5].Country = "Japan";
    cc[5].Population = 127338621;
    cc[5].Continent = "Asia";
    cc[6].Country = "Nigeria";
    cc[6].Population = 173615345;
    cc[6].Continent = "Africa";
    cc[7].Country = "Pakistan";
    cc[7].Population = 182142594;
    cc[7].Continent = "Asia";
    cc[8].Country = "Russian Federation";
    cc[8].Population = 143499861;
    cc[8].Continent = "Europe";
    cc[9].Country = "United States";
    cc[9].Population = 316128839;
    cc[9].Continent = "America";
    btnDisplay_Click(sender, e);
}

Following is the code of the click event of the Display button to display an alphabetical list of the countries:

C#
protected void btnDisplay_Click(object sender, EventArgs e)
{
    Label2.Text = "Alphabetical List";
    var info = from i in cc select i;
    GridView1.DataSource = info;
    GridView1.DataBind();
}

The above code takes the data from the array and binds it to the GridView.

The following code is used to sort the data in ascending and descending orders:

C#
protected void btnAsc_Click(object sender, EventArgs e)
{
    Label2.Text = "In Ascending Order of Population";
    var info = from i in cc orderby i.Population select i;
    GridView1.DataSource = info;
    GridView1.DataBind();
}
protected void btnDesc_Click(object sender, EventArgs e)
{
    Label2.Text = "In Descending Order of Population";
    var info = from i in cc orderby i.Population descending select i;
    GridView1.DataSource = info;
    GridView1.DataBind();
}

As shown above, the orderby query operator sorts the data in the ascending or descending order of population.

The following code groups the country information on the basis of continents and displays the Number of Countries, Total Population and Average Population in different continents:

C#
protected void btnGroup_Click(object sender, EventArgs e)
{
    Label2.Text = "Continent Wise Group Data";
    var info = from i in cc
               orderby i.Continent
               group i by i.Continent into g
               select new
               {
                   Continent = g.Key,
                   NumberOfCountries = g.Count(),
                   TotalPopulation = g.Sum(s => s.Population),
                   AveragePopulation = g.Average(a => a.Population)
               };
    GridView1.DataSource = info;
    GridView1.DataBind();
}

The groupby query operator produces group results using group functions like Count(), Sum(), Average(), etc.

The following code is used to filter data on the basis of the country name specified in a textbox:

C#
protected void btnShow_Click(object sender, EventArgs e)
{
    Label2.Text = "Data Filtered by Country Name";
    var info = from i in cc where i.Country.ToUpper() == txtCountry.Text.Trim().ToUpper() select i;
    GridView1.DataSource = info;
    GridView1.DataBind();
}

The where operator is used to filter the data according to the country name entered in the textbox.

Points of Interest

LINQ provides an easy and efficient way to work with different data sources.

I have used Microsoft Visual Studio Express 2013 for Web to develop this web application.

License

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


Written By
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with iFuture Technologies(India) as a Senior Faculty. I enjoy programming as a hobby. During my career I have seen the growth and decline of many technologies, many of them being my favorites like Flash, WPF, Windows Mobile Development. Few of my current favorites are Android, Xamarin and Python, though I also like traditional and evergreen languages like PHP, C#, Visual Basic and Java.

Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

 
QuestionThanks a lot Pin
Member 1077639810-Sep-15 18:56
Member 1077639810-Sep-15 18:56 
GeneralMy vote of 3 Pin
jackmos17-Sep-14 6:56
professionaljackmos17-Sep-14 6:56 
GeneralMy vote of 3 Pin
Lisa Shiphrah17-Sep-14 1:44
Lisa Shiphrah17-Sep-14 1:44 
QuestionA couple of suggestions Pin
George Swan16-Sep-14 19:43
mveGeorge Swan16-Sep-14 19:43 
AnswerRe: Acouple of suggestions Pin
Azim Zahir16-Sep-14 20:25
Azim Zahir16-Sep-14 20:25 
GeneralMy vote of 3 Pin
Sandeep Singh Shekhawat16-Sep-14 18:17
professionalSandeep Singh Shekhawat16-Sep-14 18:17 
GeneralMy vote of 4 Pin
Afzaal Ahmad Zeeshan16-Sep-14 7:40
professionalAfzaal Ahmad Zeeshan16-Sep-14 7:40 
GeneralMy vote of 4 Pin
Mladen Borojevic16-Sep-14 7:02
professionalMladen Borojevic16-Sep-14 7:02 
simple but informative
GeneralRe: My vote of 4 Pin
Azim Zahir16-Sep-14 18:24
Azim Zahir16-Sep-14 18:24 
GeneralMy vote of 3 Pin
ViipiinTyagi16-Sep-14 5:58
professionalViipiinTyagi16-Sep-14 5:58 

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.