CodeBlanks Logo Icon CodeBlanks

Summary - LINQ methods

C# course · Intermediate · Lesson 99/116

Combine Any, Sum, Distinct and Take to write a sales report.

Summary - LINQ methods

In this group you learned extra LINQ methods: Any/All condition checks, Count/Sum/Average/Min/Max aggregates, Distinct/Contains set ops, Take/Skip slicing, ToDictionary/ToList conversion.

In the final lesson you will write a sales report: check with Any whether there is at least one big sale, sum amounts with Sum, dedupe customers with Distinct, and show the top three sales with Take.

Exercise Write a sales report

In the sales list: (1) check with Any whether there is at least one sale over 1000 and print the result; (2) print the total of all amounts with Sum; (3) sort with OrderByDescending and print the top two amounts with Take(2) in a foreach loop.

Show example solution
Console.WriteLine(sales.Any(s => s.Amount > 1000)); Console.WriteLine(sales.Sum(s => s.Amount)); foreach (var s in sales.OrderByDescending(s => s.Amount).Take(2)) Console.WriteLine(s.Amount);
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Sale
{
    public int Amount { get; set; }
}

class Program
{
    static void Main()
    {
        var sales = new List<Sale>
        {
            new Sale { Amount = 500 },
            new Sale { Amount = 1500 },
            new Sale { Amount = 800 },
            new Sale { Amount = 2000 }
        };
        Console.WriteLine(sales.Any(s => s.Amount > 1000));
        Console.WriteLine(sales.Sum(s => s.Amount));
        foreach (var s in sales.OrderByDescending(s => s.Amount).Take(2))
        {
            Console.WriteLine(s.Amount);
        }
    }
}

Exercise Find distinct amounts

Take the amounts from the sales list with Select, deduplicate with Distinct and print each in a foreach loop.

Show example solution
Build sales.Select(s => s.Amount).Distinct(), loop with foreach, print with Console.WriteLine(a).
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;

class Sale
{
    public int Amount { get; set; }
}

class Program
{
    static void Main()
    {
        var sales = new List<Sale>
        {
            new Sale { Amount = 500 },
            new Sale { Amount = 500 },
            new Sale { Amount = 800 },
            new Sale { Amount = 800 }
        };
        foreach (var a in sales.Select(s => s.Amount).Distinct())
        {
            Console.WriteLine(a);
        }
    }
}

Test yourself

  1. Which method gives the total?

    • Average()
    • Sum()
    • Distinct()
    • Take(n)
    Show answer

    Distinct() — Correct. Sum() gives the total of a numeric collection.

  2. Match each method to its purpose

    Any
    At least one
    Sum
    Total
    Distinct
    Deduplicate
    Take
    First n elements

All lessons in Intermediate