I believe LINQ is a very nice advancement in creating database oriented applications as it allows us to separate application logic from the database. I have been using LINQ to SQL in my recent reporting application and have used various queries with ease.
With the power of Anonymous Types, I was able to create a number of reports with different grouping senarios. Anonymous Types as defined in the C# programming guide:
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler.
Let’s look at a few ways of Grouping using Anonymous Types. Before we start, displayed below is the sample data used in the queries below:
Simple Group by Anonymous Type – Grouping by Month and Year in a Date
The purpose of this query is to group transactions in the table and retrieve a list of unique months and years in a simple list.
Group by Database Column and then by Anonymous Type – Grouping by Expense Category and Monthly Total
The purpose of this query is to group all database records by Category first and then display a Total Expense based on the month in a simple list.
Group by Anonymous Type and then by Database Column – Grouping by Month and then by Expense Category and Category Total
The purpose of this query is the opposite of the group query 2. We will first group by the Month and then group by the Category Total:
With SQL you can seamlessly do all of the above on XML, CSV files or .NET Objects as well.
Recommend Resources to Learn more about LINQ to SQL
- Mike Taulty’s – Introduction to LINQ Videos
- Scott Gu’s – Highly Recommended
- Part 1: Introduction to LINQ to SQL
- Part 2: Defining our Data Model Classes
- Part 3: Querying our Database
- Part 4: Updating our Database
- Part 5: Binding UI using the ASP:LinqDataSource Control
- Part 6: Retrieving Data Using Stored Procedures
- Part 7: Updating our Database using Stored Procedures
- Part 8: Executing Custom SQL Expressions
- Part 9: Using a Custom LINQ Expression with the <asp:LinqDatasource> control