One of the powerful scenarios that anonymous types makes
easy is the ability to easily perform hierarchical shape projections of data
with a minimum amount of code.
For example, I could write the below LINQ expression
to query all products from the Northwind database whose price is
greater than $50, and then shape the returned products in a hierarchical
structure sorted by the Products' stock reorder level (using the "group
into" clause supported by LINQ query syntax):
Figure 8
When the above code is run in ASP.NET, I'll get the below
output rendered in my browser:
Figure 9
I could likewise do nice hierarchical shapings based on JOIN
results. For example, the below code creates a new anonymous type with
some standard product column properties, as well as a hierarchical
sub-collection property that contains the orderdetails of the 5 most recent
orders that customers have placed for that particular product:
Figure 10
Notice how I can neatly traverse the hierarchical
data. Above I'm looping over the product query, and then drilling into
the collection of the last 5 orders for each product. As you can see, I
have full intellisense and compile-time checking everywhere (even on properties
of objects within the nested sub-collection of order details on the anonymous
type).