How to use LINQ group clause to group results in C#

Web developers can use LINQ group clause to group their results based on a key that they specify. For example Web developers could specify that the results should be grouped by the City so that all clients from New York or San Francisco are in individual groups. In this case client.City is the key.

 

var qryClientsByCity =

from client in clients

group client by client.City into clientGroup

select clientGroup;

 

 

foreach (var clientGroup in qryClientsByCity)

{

foreach (Client client in clientGroup)

{

Console.WriteLine(“{0}”, client.FirstName);

}

}

 

When Web developers end a query with a group clause, their results take the form of list of lists. Each element in the list is an object that has a Key member and a list of elements that are grouped under that key. When Web developers iterate over a query that produces a sequence of groups, they have to use an outer loop to iterate over each group and the inner loop to iterate over each group’s members.

 

If Web developers have to refer to the results of a group operation, they can use the into keyword to create an identifier that can be queried further. The following query returns only those groups that contain more than two clients:

 

// clientQuery is an IEnumerable<IGrouping<string, Client>>

var clientQuery =

from client in clients

group client by client.City into clientGroup

where clientGroup.Count() > 2

orderby clientGroup.Key

select clientGroup;