Custom Classes and LINQ To SQL Group By

I spent a good part of my morning trying to get LTS to return my custom class as a result of a group by instead of an anonymous type. Most of the samples I found on the web for Group By returned anonymous types and the ones that didn't were from early versions and I couldn't get them to work.

The problem I was having was getting the column I was grouping on mapped. I created a class called DescriptionCounts that had two properties Description (string) and Count (integer). The following code will correctly map a group by query to this class.

Dim i = From b In dc.Barriers _  
  Group By b.BarrierType.Description Into g = Group _ 
  Select New DescriptionCounts _ 
  With {.Description = Description, .Count = g.Count}

The main thing to notice is that when the Description property gets mapped, it is mapped to a variable named Description (.Description = Description -- notice that there is no prefix) and not to a property of b.

All of the aggregate functions require that you use the Group command (g = Group).

Technorati Tags: ,

Comments

Popular posts from this blog

Migrating Legacy Apps to the New SimpleMembership Provider

Windows 8 Keyboard Shortcuts

Get Asp.Net Profile properties from Sql