[Solved] C# LINQ queries within queries and selecting groups


The first method should use this method: https://msdn.microsoft.com/en-us/library/vstudio/bb549393(v=vs.100).aspx

Something like:

return students.GroupBy(student => student.Level, (level, students) => new Tuple(level, students.Count())); 

Sorry I’m unable to test this, but basically like your version I’m using a lambda to say Group all students by level. The second lambda tells the method what to do with those groups. In this instance, for each group, I’m creating a tuple with the level and the count of students in each group.

Your return value should be changed to IEnumerable<Tuple<ClassLevel, int>> which could easily be converted to a Dictionary if you wished.

I can’t guess at the syntax for solving your second method without a compiler. But this questions uses Max: LINQ Using Max() to select a single row

Edit
This version appears to at least compile. Hopefully, you arrived at something similar

    public static Dictionary<ClassLevel, int> StudentsPerClassLevel(this IEnumerable<Student> students)
    {
        return students.GroupBy(student => student.ClassLevel, 
            (level, s) => new Tuple<ClassLevel, int>(level, s.Count())).ToDictionary(t => t.Item1, t => t.Item2);

    }

4

solved C# LINQ queries within queries and selecting groups