How to Use LINQ.GroupBy
LINQ query expressions intentionally look like SQL, because SQL is a non-procedural query language that many developers are already familiar with, so it gives developers a familiar frame of reference.
One of the fundamental differences between LINQ and SQL is that where SQL always projects rectangular result sets, LINQ has the capability of projecting hierarchical result sets. This hierarchical result set can be demonstrated in the code below, which 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.
LINQ.GroupBy Example
// anon typed array
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 }
};// group by the age
var groupedByAge =
people.GroupBy(s => s.Age);
// loop through and print results
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();
}
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 }
loading...
loading...
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
