0
0
CsharpHow-ToBeginner · 3 min read

How to Find Minimum Value in Array in C#

To find the minimum value in an array in C#, use the Min() method from System.Linq. For example, int minValue = array.Min(); returns the smallest number in the array.
📐

Syntax

The syntax to find the minimum value in an array uses the Min() method from the System.Linq namespace.

  • array.Min(): Returns the smallest element in the array.

Make sure to include using System.Linq; at the top of your code file.

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 5, 3, 9, 1, 6 };
        int minValue = numbers.Min();
        Console.WriteLine(minValue);
    }
}
Output
1
💻

Example

This example shows how to find the minimum value in an integer array using Min(). It prints the smallest number to the console.

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 10, 20, 5, 15, 30 };
        int minValue = numbers.Min();
        Console.WriteLine($"The minimum value is: {minValue}");
    }
}
Output
The minimum value is: 5
⚠️

Common Pitfalls

Common mistakes when finding the minimum in an array include:

  • Not including using System.Linq;, which causes Min() to be undefined.
  • Calling Min() on an empty array, which throws an exception.
  • Trying to find the minimum in a null array, which causes a NullReferenceException.

Always check that the array is not empty or null before calling Min().

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] emptyArray = { };

        // Wrong: This will throw an InvalidOperationException
        // int minValue = emptyArray.Min();

        // Right: Check if array has elements
        if (emptyArray != null && emptyArray.Length > 0)
        {
            int minValue = emptyArray.Min();
            Console.WriteLine(minValue);
        }
        else
        {
            Console.WriteLine("Array is empty or null.");
        }
    }
}
Output
Array is empty or null.
📊

Quick Reference

Summary tips for finding minimum in array:

  • Use array.Min() from System.Linq.
  • Always include using System.Linq;.
  • Check array is not empty or null before calling Min().
  • Works with arrays of numbers and other comparable types.

Key Takeaways

Use Min() from System.Linq to find the smallest value in an array.
Always include using System.Linq; to access Min().
Check that the array is not empty or null before calling Min() to avoid errors.
Min() works on arrays of numbers and other types that can be compared.