As I mentioned earlier in this blog post, there is
absolutely no difference from a CLR perspective between an anonymous type and
an explicitly defined/named type. Anonymous types and the var
keyword are purely "syntactic sugar" that avoid you having to
type code - the runtime semantics are the same as using explicitly defined
types.
Among other things, this means that all of the standard .NET
type reflection features work with anonymous types - which means that features
like databinding to UI controls work just fine with them. For example, if
I wanted to display the results of my previous hierarchical LINQ
query, I could define an <asp:gridview> control within a .aspx page
like below:
Figure 11
The .aspx above contains a gridview with 2
standard boundfield columns, and one templated field column that contains
a nested <asp:bulletedlist> control that I'll use to display
the product's hierarchical orderdetail sub-results.
I could then write the below LINQ code to
perform my hierarchical query against the database and databind the
custom-shaped results against the GridView to display:
Figure 12
Because the GridView supports binding against
any IEnumerable<T> sequence, and uses reflection to retrieve property
values, it will work just fine against the anonymous type I'm using
above.
At runtime the above code will produce a
simple grid of product details with a hierarchical list of their recent order
quantities like so:
Figure 13