CodeBlanks Logo Icon CodeBlanks

Summary - Advanced LINQ

C# course · Advanced · Lesson 30/83

Combine GroupBy, Join and Aggregate to write a sales analysis report.

Summary - Advanced LINQ

In this group you learned five advanced LINQ operators. GroupBy groups items by key, Join matches two sequences with an inner join, GroupJoin builds a hierarchical join.

Aggregate folds a sequence to one value, Zip combines two sequences in parallel. Two small tasks now combine them.

Exercise Group by first letter

Group the words list below by first letter using GroupBy. Print how many words each letter has with Console.WriteLine.

Show example solution
" + g.Count().
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var words = new List<string> { "apple", "apricot", "banana" };
        var groups = words.GroupBy(w => w[0]);
        foreach (var g in groups)
        {
            Console.WriteLine(g.Key + ": " + g.Count());
        }
    }
}

Exercise Zip two lists together

Combine the names and scores lists below with Zip. Print each pair as name: score with Console.WriteLine.

Show example solution
" + s); then write foreach (var p in pairs) Console.WriteLine(p);.
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var names = new List<string> { "Ayşe", "Ali" };
        var scores = new List<int> { 90, 85 };
        var pairs = names.Zip(scores, (n, s) => n + ": " + s);
        foreach (var p in pairs)
        {
            Console.WriteLine(p);
        }
    }
}

Where advanced LINQ fits

GroupBy, Join and Aggregate reshape data; Zip brings two sources side by side. These operators enable declarative data processing.

The next section moves to expression trees: LINQ query providers read those trees and translate them into target languages like SQL.

Test yourself

  1. Which one groups items?

    • Aggregate
    • GroupBy
    • Zip
    • Join
    Show answer

    GroupBy — Correct. GroupBy splits items into groups by key.

  2. Complete the Aggregate call

    var product = numbers.____((acc, n) => acc * n);
    Show answer
    var product = numbers.Aggregate((acc, n) => acc * n);

All lessons in Advanced