Start learning free

LESSON 271 OF 674 · TUPLES, SORTING & BUILT-INS

Min, Max and Sum in C#: LINQ Built-ins

Lesson Read the full explanation

TL ; DR:

LINQ gives every list Min(), Max() and Sum().

They return its smallest value, its largest value and its total.


List<int> prices = new List<int>(new[] {4, 9, 2, 7});

Console.WriteLine(prices.Min());    // 2

Console.WriteLine(prices.Max());    // 9

Console.WriteLine(prices.Sum());    // 22


Full lesson:

In Maximum Number In Array, a loop found the largest value. In Sum of Numbers, a loop added numbers up. These jobs come up all the time. LINQ has them ready-made.

  • nums.Min() gives the smallest value of nums.
  • nums.Max() gives the largest value.
  • nums.Sum() adds all the values up.

They come from LINQ, like Where and Select. So the file needs using System.Linq at the top. This lesson already has it. They work the same on a List and on an array.

Math.Max(a, b) from Maximum Number In Array compares two values. Max() looks at a whole list.

Watch out for an empty list. Min() and Max() throw an InvalidOperationException on it. An empty list has no smallest value. Check nums.Count > 0 first. Sum() of an empty list is 0.


Your task

minutes holds how many minutes you practiced coding on each day of a week.

Store the shortest day in shortest and the longest day in longest. Store the week's total in total.

Use the built-ins from this lesson. The code at the bottom prints all three.

Expected output:

shortest = 15
longest = 60
total = 235
STEP 1 OF 3
    Ctrl + Enter to check

    C# · TUPLES, SORTING & BUILT-INS

    Min Max Sum in C#, explained

    Three ready-made jobs

    Finding the largest value and adding numbers up are jobs a loop can do, and they come up so often that LINQ has them built in. For a List<int> named nums:

    • nums.Min() returns the smallest value.
    • nums.Max() returns the largest value.
    • nums.Sum() returns the total of all the values.
    List<int> prices = new List<int>(new[] {4, 9, 2, 7});
    
    Console.WriteLine(prices.Min());    // 2
    Console.WriteLine(prices.Max());    // 9
    Console.WriteLine(prices.Sum());    // 22
    

    These are LINQ methods, like Where and Select, so a file of your own needs using System.Linq; at the top. The lesson's editor already has it. They work on anything you can loop over, so an array behaves the same way: for int[] arr = {4, 9, 2, 7}, the calls arr.Min(), arr.Max() and arr.Sum() give 2, 9 and 22.

    Min() versus Math.Min

    Math.Max(a, b) compares exactly two values. Max() on a list looks at all of them. Both exist, and they do different jobs.

    What they replace

    Each call stands in for a loop you have already written: a variable that starts at the first value and is updated as you go for Min() and Max(), and a total that starts at 0 and grows by each value for Sum(). The built-in version is shorter and has no starting value to get wrong, such as starting a maximum at 0 when every number is negative. A loop is still the right tool when you need more than one of these in a single pass, or when you must also know where the smallest value is.

    Gotchas

    • An empty list. It has no smallest and no largest value, so Min() and Max() throw an InvalidOperationException with the message "Sequence contains no elements". Sum() of an empty list is 0. If a list might be empty, check nums.Count > 0 first.
    • Overflow in Sum(). Plain int arithmetic wraps around silently, but Sum() on ints checks for overflow. new List<int>{2000000000, 2000000000}.Sum() throws an OverflowException. Use long values, or Select(n => (long)n).Sum(), if totals can be that large.
    • Forgetting the parentheses. prices.Min() is a method call. prices.Min without them is a different thing and does not compile as a number.

    The lesson's task

    minutes holds how many minutes someone practiced coding on each day of a week. The task is to store the shortest day, the longest day and the week's total in three int variables, and the code at the bottom prints them. Each one is one call, with no loop:

    List<int> minutes = new List<int>(new[] {25, 40, 15, 60, 30, 45, 20});
    
    int shortest = minutes.Min();
    int longest = minutes.Max();
    int total = minutes.Sum();
    
    Console.WriteLine("shortest = " + shortest);
    Console.WriteLine("longest = " + longest);
    Console.WriteLine("total = " + total);
    

    It prints:

    shortest = 15
    longest = 60
    total = 235
    

    Step by step

    1. Below the list, declare int shortest = minutes.Min();. One call looks at every value.
    2. Declare int longest = minutes.Max(); the same way.
    3. Declare int total = minutes.Sum();. The three lines that print the results are already in the starter code and use these three names exactly.

    The shortest day is 15 minutes, the longest is 60, and the seven days add up to 235.

    Key takeaways

    • Min(), Max() and Sum() replace a loop with one call.
    • They need using System.Linq; and work on lists and arrays.
    • Min() and Max() throw on an empty list, while Sum() returns 0.
    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free