Monday, August 27, 2007

First Experiences With VS2K8 Part 5 (Data Shaping)

This is the fifthin a series of posts I'm going to be making about my experiences with Visual Studio 2008 and .NET3.5. You might also be interested in the other posts which are linked at the right. This is another quick hit post to talk about something I've been doing a lot of with LINQ that I think is pretty damn powerful. MS calls is data shaping and the basic idea is that you can use LINQ queries to 'reshape' your data in order to make it easier to work with in a given context. That's probably not too helpful a description without an example so here goes. Let's say in my order application I need to create a quick reporting page that lists all of our customers' order totals. The page needs three columns: cust id, cust name and total for all orders. For the purpose of this illustration let's assume that I've already got a method that returns a Dictionary where the keys are my customers and the values are the sum total of each customer's orders. Without LINQ I could simply bind a GridView to this Dictionary and then specify a ColumnTemplate for cust id, cust name and orders total. With LINQ however I don't even need to specify those ColumnTemplates. Instead I can use LINQ to shape the data before I bind like so: var query = from cust in custOrdersDict.Keys select new { ID = cust.Id, Name = string.Concat(cust.FirstName, " ", cust.LastName), OrdersTotal = custOrdersDict[key].ToString("C") }; I then bind my plain vanilla GridView to 'query' and I get exactly what I want. My column headers are 'ID', 'Name' and 'OrdersTotal' and the values in the columns are formatted just how I specified. Name is a concatenation of first and last name and the OrdersTotal value is formatted as currency. This seems quite useful to me because now my GridView is not so intimately tied to the data it is being bound to. For instance if I needed to add City/State info to the report I would not have to touch my GridView at all. I would simply modify my LINQ query as follows: var query = from cust in custOrdersDict.Keys select new { ID = cust.Id, Name = string.Concat(cust.FirstName, " ", cust.LastName), Location = string.Concat(cust.City, ", ", cust.State), OrdersTotal = custOrdersDict[key].ToString("C") }; And now when I bind I get a new Location column. And I didn't have to mess with my GridView at all. Pretty neat!

No comments: