Thursday, September 3, 2009

An Extensive Examination of LINQ: Grouping and Joining Data

An Extensive Examination of LINQ: Grouping and Joining Data

Introduction
As discussed in An Introduction to LINQ, one of the cornerstones of LINQ is the standard query operators, which are a set of extension methods on the IEnumerable interface added to the .NET Framework version 3.5. The standard query operators can be applied to any enumeration - any collection of "things." In The Standard Query Operators installment we looked at some of the more common query operators, such as Where, Select, OrderBy, and others. Each standard query operator can be classified as a certain type of operator. There are aggregation operators like Count, Sum, and Max; element operators like First, Last, and ElementAt let you pick out a specific element from a sequence; and the ordering operators OrderBy and OrderByDescending order the elements of a sequence based on a specified sorting criteria.

Another class of query operators that we've yet to explore are grouping and joining operators. The grouping and joining operators work with two (or more) sequences and combine them together, much like how a JOIN in SQL combines records from two (or more) tables into a single resultset. Through LINQ's standard query operators (or via its query syntax), it is possible to perform: nested (or grouped) queries; cross joins, or the Cartesian product of two sequences; inner joins; and left outer joins.

Examining the Sample Data
The examples in this article look at how to create LINQ queries that group and join the same set of sample data. If you download the demos (available at the end of this article) you'll find a class file named FauxNorthwind.cs in the App_Code/CSCode folder. This file defines a namespace (FauxNorthwind) and three classes within that namespace. The first two, Category and Product, mimic the schema of the Category and Product tables in the Northwind database. The Category class has CategoryId and CategoryName properties, while the Product class has the properties ProductId, ProductName, Category, UnitPrice, and Discontinued.

public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}

public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public Category Category { get; set; }
public decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
}




View Full Details...............................

No comments:

Post a Comment