One of the new C# and VB language features that LINQ can
take advantage of is support for “Anonymous Types”. This allows you to easily
create and use type structures inline without having to formally declare their
object model (instead it can be inferred by the initialization of the data).
This is very useful to “custom shape” data with LINQ queries.
For example, consider a scenario where you are working
against a database or strongly-typed collection that has many properties – but
you only really care about a few of them. Rather than create and work against
the full type, it might be useful to only return those properties that you
need. To see this in action we’ll create a step6.aspx file like so:
Listing 15
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Step6.aspx.cs"
Inherits="Step6" %>
<html>
<body>
<form id="form1" runat="server">
<div>
<h1>Anonymous Type</h1>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
And within our code-behind file we’ll write a LINQ query
that uses anonymous types like so:
Listing 16
using System;
using System.Web.UI;
using System.Query;
public partial class Step6 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TravelOrganizer travel = new TravelOrganizer();
GridView1.DataSource = from location in travel.PlacesVisited
orderby location.City
select new {
City = location.City,
Distance = location.Distance
};
GridView1.DataBind();
}
}
Note that instead of returning a “location” from our select
clause like before, I am instead creating a new anonymous type that has two
properties – “City” and “Distance”. The types of these properties are
automatically calculated based on the value of their initial assignment (in
this case a string and an int), and when databound to the GridView produce an
output like so:
Figure 7
<img border=0 width=276 height=496src="/ArticleFiles/922/image006.jpg">