Partilhar via


Grouping

[Blog Map]  [Table of Contents]  [Next Topic]

LINQ query expressions look a lot like SQL, and that is intentional.  SQL is a non-procedural query language that many developers are already familiar with, so to the extent that LINQ looks like SQL, it gives developers a familiar frame of reference.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOCHowever, one of the fundamental differences between LINQ and SQL is that whereas SQL always projects rectangular result sets, LINQ has the capability of projecting hierarchical result sets.

The following code creates an array of an anonymous type containing two properties each.  It then groups them by age.  We can then iterate through the results using nested for loops.

The following code is attached to this page.

var people = new[] {
new { Name = "Bob", Age = 3 },
new { Name = "Bill", Age = 3 },
new { Name = "Mary", Age = 4 },
new { Name = "June", Age = 3 },
new { Name = "Nancy", Age = 4 },
new { Name = "Shelly", Age = 4 },
new { Name = "Cheryl", Age = 3 },
new { Name = "Joe", Age = 3 }
};

var groupedByAge =
people.GroupBy(s => s.Age);

foreach (var group in groupedByAge)
{
// group implements IGrouping
Console.WriteLine("Group of people aged {0}", group.Key);
foreach (var person in group)
{
// person is an instance of the above anonymous type
Console.WriteLine(person);
}
Console.WriteLine();
}

This example produces the following output:

Group of people aged 3
{ Name = Bob, Age = 3 }
{ Name = Bill, Age = 3 }
{ Name = June, Age = 3 }
{ Name = Cheryl, Age = 3 }
{ Name = Joe, Age = 3 }

Group of people aged 4
{ Name = Mary, Age = 4 }
{ Name = Nancy, Age = 4 }
{ Name = Shelly, Age = 4 }

Using a query expression, the query looks like this:

var groupedByAge =
from p in people
group p by p.Age;

There are lots of options for grouping, and this tutorial won't go into all of them.  However, the notion that we can project a hierarchical result set is important.  Later on in the tutorial, we'll see a new grouping extension method that gives us the ability to group in a way that the standard grouping extension methods don't support.

[Blog Map]  [Table of Contents]  [Next Topic]

Grouping.cs

Comments