Using LINQ with ASP.NET (Part 1)
page 4 of 12
by Scott Guthrie
Feedback
Average Rating: 
Views (Total / Last 10 Days): 53818/ 81

Step 2: Using Richer Collections

Searching an array of strings is not terribly interesting (although sometimes actually useful).  More interesting would be the ability to search and work against richer collections of our own making.  The good news is that LINQ makes this easy.  For example, to better track trips I can create a simple class called “Location” in my project below:

Listing 5

using System;
public class Location
{
    // Fields
    private string _country;
    private int    _distance;
    private string _city;
 
    // Properties
    public string Country
    {
        get { return _country; }
        set { _country = value; }
    }
    public int Distance
    {
        get { return _distance; }
        set { _distance = value; }
    }
 
    public string City
    {
        get { return _city; }
        set { _city = value; }
    }
}

This exposes 3 public properties to track the County, City name and Distance from Seattle.  I can then create a Step2.aspx file with a GridView control that defines 3 columns like so:

Listing 6

<%@ Page Language="C#" CodeFile="Step2.aspx.cs" Inherits="Step2" %>
<html>
<body>
    <form id="form1" runat="server">
 
    <h1>Cities and their Distances</h1>
    
    <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
       <Columns>
          <asp:BoundField HeaderText="Country" DataField="Country" />
          <asp:BoundField HeaderText="City" DataField="City" />
          <asp:BoundField HeaderText="Distance from Seattle" DataField="Distance" />
       </Columns>
    </asp:GridView>
    
    </form>
</body>
</html>

I can then populate a collection of Location objects and databind it to the Grid in my code-behind like so:

Listing 7

using System;
using System.Collections.Generic;
using System.Web;
using System.Query;
 
public partial class Step2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Location> cities = new List<Location>{
                                    new Location
{ City="London", Distance=4789, Country="UK" },
                                    new Location
{ City="Amsterdam", Distance=4869, Country="Netherlands" },
                                    new Location
{ City="San Francisco", Distance=684, Country="USA" },
                                    new Location
{ City="Las Vegas", Distance=872, Country="USA" },
                                    new Location
{ City="Boston", Distance=2488, Country="USA" },
                                    new Location
{ City="Raleigh", Distance=2363, Country="USA" },
                                    new Location
{ City="Chicago", Distance=1733, Country="USA" },
                                    new Location
{ City="Charleston", Distance=2421, Country="USA" },
                                    new Location
{ City="Helsinki", Distance=4771, Country="Finland" },
                                    new Location
{ City="Nice", Distance=5428, Country="France" },
                                    new Location
{ City="Dublin", Distance=4527, Country="Ireland" }
                                };
 
        GridView1.DataSource = from location in cities
                               where location.Distance > 1000
                               orderby location.Country, location.City 
                               select location;
 
        GridView1.DataBind();
    }
}

The above code-behind shows off a few cool features.  The first is the new C# 3.0 support for creating class instances, and then using a terser syntax for setting properties on them: 

Listing 8

new Location { City="London", Distance=4789, Country="UK" }

This is very useful when instantiating and adding classes within a collection like above (or within an anonymous type like we’ll see later).  Note that rather than use an array this time, I am using a Generics based List collection of type “Location”.  LINQ supports executing queries against any IEnumerable<T> collection, so can be used against any Generics or non-Generics based object collections you already have. 

For my LINQ query I’m then returning a collection of all cities that are more than 1000 miles away from Seattle.  I’ve chosen to order the result in alphabetical order – first by country and then by city name.  The result of this LINQ query is again dictated by the type of the “location” variable – so in this case of type “Location”:

Listing 9

        IEumerable<Location> result = from location in cities
                                      where location.Distance > 1000
                                      orderby location.Country, location.City 
                                      select location;

When I databind this result against the GridView I get a result like so:

Figure 4

<img border=0 width=392 height=458src="/ArticleFiles/922/image004.jpg">

View Entire Article

User Comments

Title: linq   
Name: rohit
Date: 2012-10-11 5:04:12 AM
Comment:
thanks a lot,but need more explanation
Title: uk   
Name: hjkhjk
Date: 2012-07-30 2:22:48 AM
Comment:
hjkhjkhjkhjk
Title: Linq   
Name: hanston
Date: 2012-06-04 2:02:15 PM
Comment:
thanks a lot....but the images aren't shown.......
Title: Language Integrated Query   
Name: Daniel Kamroon
Date: 2012-03-14 7:22:12 AM
Comment:
Thank you very much. This has become my best material on LINQ topic. You made it very simple and understandable, thanks for sharing with us. Some other good articles on LINQ I was found over internet during searching this topic which also explained very well about LINQ, URL links of those posts are....
http://msdn.microsoft.com/en-us/library/bb907622.aspx
http://mindstick.com/Articles/9ca8fabd-49ef-4e4d-855b-74fc523d9138/?LINQ%20%28Language%20Integrated%20Query%29
http://www.codeproject.com/Articles/188935/LINQ-Demo-with-ASP-NET-Web-Application

Lastly, I would like to say thanks to everyone for your precious post.
Title: Sql Linq -simple query   
Name: Manish Vala
Date: 2011-02-12 4:23:52 AM
Comment:
protected void Page_Load(object sender, EventArgs e)
{
//DateTime d = DateTime.Now;

string[] Name = {" Manish"," Sunil", "Rohan", "Ashok", "Mahendra" };

GridView1.DataSource = from name in Name where name.Length > 5 orderby name select name.ToUpper();
GridView1.DataBind();}
Title: SQL LINQ-A query   
Name: Subhashini Janakiraman
Date: 2010-12-16 2:48:23 AM
Comment:
In the statement below which you have used,I want to know what Northwind refers to.Is it a dataset or a class?.Please reply me so.
Northwind db=new Northwind();
Title: thanks alot   
Name: avrail
Date: 2010-09-26 1:38:46 AM
Comment:
thanks a lot for this article
Title: Using LINQ with ASP.NET   
Name: S.Kumar
Date: 2010-04-08 3:52:48 PM
Comment:
Really a nice article, gave me a nice overview about LINQ
Title: er   
Name: sdf
Date: 2009-11-14 5:46:55 AM
Comment:
protected void Page_Load(object sender, EventArgs e)
{
string[] cities = { "London", "Amsterdam", "San Francisco", "Las Vegas",
"Boston", "Raleigh", "Chicago", "Charlestown",
"Helsinki", "Nice", "Dublin" };

GridView1.DataSource = from city in cities
where city.Length > 4
orderby city
select city.ToUpper();

GridView1.DataBind();
}
Title: nice   
Name: vice
Date: 2009-11-14 5:45:23 AM
Comment:
GridView1.DataSource = from city in cities
where city.Length > 4
orderby city
select city.ToUpper();
Title: jeyakumar   
Name: jayakumar
Date: 2009-11-14 5:40:46 AM
Comment:
it looking like me
Title: ok   
Name: kumar
Date: 2009-11-14 5:37:29 AM
Comment:
nice but not understand
Title: Topics   
Name: Dhanya
Date: 2009-10-19 6:09:06 AM
Comment:
I am not understand this topics..
Title: Trying To Get a Handle On This LINQ Stuff   
Name: Vibha Kant Pandey
Date: 2009-04-21 3:05:18 AM
Comment:
This article really enabled me to understand the concept of linq. the only problem i faced with this article is that i was not redirected to the correct place to download Linq May ctp
Title: About LINQs in ASP.NET   
Name: SitaRamReddy.Vempada
Date: 2009-04-01 5:47:16 AM
Comment:
This article help me a lot in LINQ concept, I thank to all who are in this unit

Thanks & Regards,
srvempada
Title: Using LINQ with ASP.NET (Part 1)   
Name: joseph jelasker
Date: 2009-03-28 1:52:20 AM
Comment:
This article really enabled me to understand the concept of linq. the only problem i faced with this article is that i was not redirected to the correct place to download Linq May ctp


Thanks a lot
Title: LINQ in 2005 and 2008   
Name: Manigandan
Date: 2008-12-16 6:38:07 AM
Comment:
1.We are having this LINQ concept in VS2005 itself...
What is extra facility added in VS2008.

2.If i want to install LINQ separately in VS2005, What is the software that i have to install?
Title: Good one   
Name: Shailendra
Date: 2008-12-09 2:24:22 AM
Comment:
Thanks for all, its very easy to know about linq from these articles.

thanks once again
Title: Trying To Get a Handle On This LINQ Stuff   
Name: D Wiley
Date: 2008-11-21 9:21:36 AM
Comment:
This is on of the best walkthroughs I have seen on the subject.
Title: Leraning LINQ   
Name: Manjeev kumar singh
Date: 2008-10-03 4:00:41 AM
Comment:
This one is most useful article LINQ on web. its really good start for how is beginner in LINQ....
Really thanks
Title: Using Richer Collections   
Name: Nithya K
Date: 2008-09-18 6:58:04 AM
Comment:
Now i got .Its my mistake.
It is very useful
Title: Using Richer Collections   
Name: Nithya K
Date: 2008-09-18 6:00:18 AM
Comment:
i got an error while executing
Title: Using Richer Collections   
Name: Nithya K
Date: 2008-09-18 5:53:19 AM
Comment:
\
\S
\
\
Title: Leraning LINQ   
Name: vanitha
Date: 2008-09-16 1:31:46 AM
Comment:
Very useful in learning the basic concepts of LINQ.
Title: Using LINQ with ASP.NET   
Name: Durai karthik M
Date: 2008-03-15 7:20:50 AM
Comment:
Very clear to understand the LINQ concept . Keep up the good work
Title: -   
Name: martin
Date: 2008-01-21 4:41:46 AM
Comment:
The images aren't shown... you need to remake the picture HTML






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-13 9:48:42 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search