How to: Perform a Subquery on a Grouping Operation (C# Programming Guide)

This topic shows two different ways to create a query that orders the source data into groups, and then performs a subquery over each group individually. The basic technique in each example is to group the source elements by using a continuation named newGroup, and then generating a new subquery against newGroup. This subquery is run against each new group that is created by the outer query. Note that in this particular example the final output is not a group, but a flat sequence of anonymous types.

For more information about how to group, see group clause (C# Reference).

For more information about continuations, see into (C# Reference). The following example uses an in-memory data structure as the data source, but the same principles apply for any kind of LINQ data source.

public void QueryMax()
    var queryGroupMax =
        from student in students
        group student by student.Year into studentGroup
        select new
            Level = studentGroup.Key,
            HighestScore =
            (from student2 in studentGroup
             select student2.ExamScores.Average()).Max()

    int count = queryGroupMax.Count();
    Console.WriteLine("Number of groups = {0}", count);

    foreach (var item in queryGroupMax)
        Console.WriteLine("  {0} Highest Score={1}", item.Level, item.HighestScore);

This example contains references to objects that are defined in the sample application in How to: Query a Collection of Objects (C# Programming Guide). To compile and run this method, paste it into the StudentClass class in that application and add a call to it from the Main method.

When you adapt this method to your own application, remember that LINQ requires version 3.5 of the .NET Framework, and the project must contain a reference to System.Core.dll and a using directive for System.Linq. LINQ to SQL, LINQ to XML and LINQ to DataSet types require additional usings and references. For more information, see How to: Create a LINQ Project.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft