jump to navigation

Linq to Objects in ASP.Net October 6, 2010

Posted by fofo in asp.net, C#, LINQ, Visual Studio 2008, Visual Studio 2010.

In this post I would like to talk about  Linq to Objects in an ASP.Net application.

In all my classes people seem to have the following answer to this question, “What kind of data can we query with LINQ?

Most people say “Well, we can query an SQL server database” . I am not very pleased when people forget the other flavors.

LINQ to Objects allow us to write “queries” over collections of objects.This is the first and most basic flavor of LINQ. LINQ to Objects enables you to perform
complex query operations against any enumerable object. By that I mean any object that implements the IEnumerable interface.

I will use Visual Studio 2010 Ultimate edition.You can use VS 2010/VS2008 Professional edition.

VS 2010/VS2008 Epxress editions will be fine for this example. I am using C# for this one.

1) Fire VS and create a new asp.net website with a name of your choice. Choose local filesystem as the location of your website files.

2)  Add a GridView web server control to the Default.aspx page.

3) Add a Class file in your website ( Add – > New item ) . I am going to have data related to football so i named it Football.cs

4) Inside the public class Football type

        public string FootballTeamName { get; set; }
        public string Manager { get; set; }
        public string TeamCaptain { get; set; }
        public int ChampionshipsWon { get; set; }

5) Now that we have a class to work with, we should create a simple generic List of the Football objects and then bind that list to the Gridview control.

6) This is the code for the generic list of the Football objects. We place this code in the Default.aspx page.

public List<Football> GetFootballData()
return new List<Football> {
new Football { FootballTeamName="Liverpool", Manager="Roy Hodgson", 
TeamCaptain="Steven Gerrard",ChampionshipsWon=18  },
new Football { FootballTeamName="ManUtd", Manager="Alex Ferguson", 
TeamCaptain="Rio Ferdinand", ChampionshipsWon=18},
new Football { FootballTeamName="Chelsea", Manager="Carlos Ancelotti", 
TeamCaptain="Frank Lampard",ChampionshipsWon=4 },
new Football { FootballTeamName="Everton", Manager="David Moyes", 
TeamCaptain="Phil Neville",ChampionshipsWon=9 }

7) Now we add the code in the Page_Load() event handling routine. We just type

 var football = GetFootballData();
 this.GridView1.DataSource = football;

8) Run your application and see the results in the web browser.

9) Imagine we want to filter our data. Let’s write the query first in a non-LINQ way.

Comment out the code in the Page_Load event handling routine.We want to query the data where the Manager is “Roy Hodgson”.

In the Page_Load event handling routine type

 var football = GetFootballData();
var query = new List<Football>();
foreach (var f in football)
if (f.Manager == "Roy Hodgson" ) query.Add(f);
this.GridView1.DataSource = query;

10) Run your application and see the in the browser the record that satisfies the criteria.

11) If we want to have more complex queries (grouping or sorting ) then the code becomes a bit hard to follow and maintain.

12) Now we will write a number of queries the “LINQ” way. We do not have to worry anymore on exactly how a query is going to be executed.

We just need to define what the query should return. The compiler must come up with a way and determine how the query will be executed.

13) Comment out the code inside the Page_Load event handling routine and type this code

        var football = GetFootballData();
        var query = from f in football
                    select f;
        this.GridView1.DataSource = query;

14) Run your application and see the results. We use the GetFootballData() method to obtain the generic list collection.Then we use the simplest LINQ query to select all the Football objects from the generic collection.

We do have new language keywords like select and from.

15) Now let’s say that we want only the Manager and FootballTeamName values. Comment out the code inside the Page_Load event handling routine and type this code

           var football = GetFootballData();
           var query = from f in football
                       select new { f.FootballTeamName, f.Manager };
           this.GridView1.DataSource = query;

Run your application and see the results.What we did here is called Projection and contains the Manager and FootballTeamName values for all the objects.

16) If we want to have some ordering(get the values back according to the object Manager descending) of the data we just re-write the code above

        var football = GetFootballData();
        var query = from f in football
                    orderby f.Manager descending
                    select new { f.FootballTeamName, f.Manager };
        this.GridView1.DataSource = query;

Run your application and see the results.

17) We do have query filters in LINQ. We can use the where clause.If we want to find how many teams won more than 10 championships we should type ( after commenting out all our code in the Page_Load )

        var football = GetFootballData();
        var query = from f in football
                    where f.ChampionshipsWon > 10
                    select f;
        this.GridView1.DataSource = query;

Run your application and see the results.

18) If we want to get only the Manager name and the team captain name for the last 2 records we should type (after commenting out all our code in the Page_Load)

        var football = GetFootballData();
        var query = (from f in football
        select new { f.Manager, f.TeamCaptain }).Reverse().Take(2);
        this.GridView1.DataSource = query;

Run your application and see the results. We use the Reverse() method that inverts the order of the elements in a sequence.

We also use the Take() method to return a specified number of elements from the start of a sequence.

This post can be very useful to people that begin to learn LINQ.Email me if you want the source code.

Hope it helps!!!



1. Arpit Jodawat - May 19, 2011

I am using this in windows application
when i do this

var football = GetFootballData();
this.GridView1.DataSource = football;

it work
but when i do some kind of filteration in it like
var football = GetFootballData();
var query = from f in football
select new { f.FootballTeamName, f.Manager };
this.GridView1.DataSource = query;

it doesnot show anything in datagrid

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: