Start learning free

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

Min, Max and Sum in C#

Lesson

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