DataBinding with Anonymous Types in C#

Written on

I wanted to use an ASP.NET repeater to bind some data to a web form, but the data in the code came from two different places. I used LINQ to join my two data collections together, but the problem was that this resulted in my query returning an IEnumerable of anonymous types. I thought that this would mean I'm not going to be able to bind these anonymous type objects to my repeater without creating a strongly typed class or struct.

It turns out that I was wrong: I can bind anonymous types to a repeater! That's pretty cool, and I'll show you how I did it. My LINQ query looked like this:

Customer[] customers = GetCustomers();
Country[] countries = GetCountries();

var query = from customer in customers
            join country in countries on customer.CountryID equals country.CountryID
            where customer.Age > 21 &&
                  country.Name == "United Kingdom"
            select new
                       {
                           CustomerName = customer.Name,
                           CountryName = country.Name
                       };

MyRepeater.DataSource = query.ToArray();
MyRepeater.DataBind();

As you can see, I'm using CustomerName from one type of object, and CountryName from another type, and joining these together into a new anonymous type.

After this, in my HTML/ASCX I can use a repeater like this:

<asp:Repeater ID="MyRepeater" runat="server">
    <ItemTemplate>
        <p>
            <%# Eval("CustomerName") %>
            lives in
            <%# Eval("CountryName") %>
        </p>
    </ItemTemplate>
</asp:Repeater>

When you think about it, this actually makes sense. Anonymous types of course are real types - it's just that the compiler generates the type for me, so I don't have to.


Comments