Binding LINQ Hierarchies to ASP.NET Controls
If you are familiar with LINQ, you know that your objects have hierarchies, that can be a challenge when binding to ASP.NET tabular controls such as the GridView. So how can you do this? Anonymous types can come to the rescue. For instance, if you want to show the customer who participated in a collection of orders, to show the relation, the following approach can be used:
var orders = this.GetAllOrders(); //Gets all orders from the data context
var orderDisplay = from order in orders
orderby order.Customer.LastName, order.OrderDate
select new
{
order.Customer.LastName,
order.Customer.FirstName,
FullName = order.Customer.LastName + " " + order.Customer.FirstName,
order.OrderDate,
order.OrderAmount
};
this.gvwOrders.DataSource = orderDisplay;
this.gvwOrders.DataBind();
Because of anonymous types, LINQ can safely show hierarchical data in a tabular control.