How to Find the Maximum Value of an Array in C#

In this article, we will discuss different ways How to find the maximum value of an array in C# and after that also find the best way to perform this task. As a programmer, we perform this task more often so we must know the best way to get high performance. Let’s start with the examples and explanations.

If you want to boost your productivity as a .NET Developer follow the below link.

Click Me.

Create an array:

To perform this task we first have to create a predefined array so we can operate on this array.

var sampleArray = new int[] { 5, 7, 30, 23, 50, 1, 19 };

Now let’s try some approaches and discuss them.

Use of Enumerable.Max to get the Maximum Value of an Array:

“Max” is the extension method of IEnumerable that doesn’t require any parameter and returns the maximum value of the array of the elements.

return sampleArray.Max(); //Output 50 

This Max() function doesn’t only work with the array of int but if you apply this to the array of strings. It will return the first alphabet order.

Use of Enumerable.MaxBy:

We can use Enumerable.MaxBy instead of the above method since the .NET 6 has been introduced.

return sampleArray.MaxBy(s => s);

With this method, we have to pass the lambda expression to get the compared value so we don’t need to sort the array to get the first or last element of the array.

We can also find the minimum value of an array by using a similar method as above.

return sampleArray.MinBy(s => s);

Simple Iteration to find the maximum value of an array:

Now let’s try how can we find the maximum value of the array by using a simple for loop.

public int GetMaxValue(int[] sampleArray)
{
    int maxElement = sampleArray[0];
    for (int index = 1; index < sampleArray.Length; index++)
    {
        if (sampleArray[index] > maxElement)
            maxElement = sampleArray[index];
    }

    return maxElement;
}

In the above code snippet, we have created a public method that is taking the array as a parameter and applying for loop on it. And after a simple operation to get the largest element returning the maximum value of an array.

Conclusion:

As we promised at the start that we will also reveal the best way to perform this task performance-wise. So all of these methods are good and none of them is too worst in any condition, but the best way is Enumerable.Max to do this task quickly. So in this article, we have discussed different ways How to find the maximum value of an array in C#. If you face any issues or have any questions do not hesitate to comment below or contact us.

Leave a Reply

Your email address will not be published.