Perform a subquery on a grouping operation

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.

For more information about continuations, see into. 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.



This example contains references to objects that are defined in the sample code in Query a collection of objects.

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 = {count}");

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

See also

LINQ Query Expressions