Is there a method to find the max of 3 numbers in C#?

C#Max

C# Problem Overview


The method should work like Math.Max(), but take 3 or more int parameters.

C# Solutions


Solution 1 - C#

You could use Enumerable.Max:

new [] { 1, 2, 3 }.Max();

Solution 2 - C#

Well, you can just call it twice:

int max3 = Math.Max(x, Math.Max(y, z));

If you find yourself doing this a lot, you could always write your own helper method... I would be happy enough seeing this in my code base once, but not regularly.

(Note that this is likely to be more efficient than Andrew's LINQ-based answer - but obviously the more elements you have the more appealing the LINQ approach is.)

EDIT: A "best of both worlds" approach might be to have a custom set of methods either way:

public static class MoreMath
{
    // This method only exists for consistency, so you can *always* call
    // MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
    // depending on your argument count.
    public static int Max(int x, int y)
    {
        return Math.Max(x, y);
    }

    public static int Max(int x, int y, int z)
    {
        // Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
        // Time it before micro-optimizing though!
        return Math.Max(x, Math.Max(y, z));
    }

    public static int Max(int w, int x, int y, int z)
    {
        return Math.Max(w, Math.Max(x, Math.Max(y, z)));
    }

    public static int Max(params int[] values)
    {
        return Enumerable.Max(values);
    }
}

That way you can write MoreMath.Max(1, 2, 3) or MoreMath.Max(1, 2, 3, 4) without the overhead of array creation, but still write MoreMath.Max(1, 2, 3, 4, 5, 6) for nice readable and consistent code when you don't mind the overhead.

I personally find that more readable than the explicit array creation of the LINQ approach.

Solution 3 - C#

Linq has a Max function.

If you have an IEnumerable<int> you can call this directly, but if you require these in separate parameters you could create a function like this:

using System.Linq;

...

static int Max(params int[] numbers)
{
	return numbers.Max();
}

Then you could call it like this: max(1, 6, 2), it allows for an arbitrary number of parameters.

Solution 4 - C#

As generic

public static T Min<T>(params T[] values) {
    return values.Min();
}

public static T Max<T>(params T[] values) {
    return values.Max();
}

Solution 5 - C#

off topic but here is the formula for middle value.. just in case someone is looking for it

Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));

Solution 6 - C#

Let's assume that You have a List<int> intList = new List<int>{1,2,3} if You want to get a max value You could do

int maxValue = intList.Max();

Solution 7 - C#

If, for whatever reason (e.g. Space Engineers API), System.array has no definition for Max nor do you have access to Enumerable, a solution for Max of n values is:

public int Max(int[] values) {
    if(values.Length < 1) {
        return 0;
    }
    if(values.Length < 2) {
        return values[0];
    }
    if(values.Length < 3) {
       return Math.Max(values[0], values[1]); 
    }
    int runningMax = values[0];
    for(int i=1; i<values.Length - 1; i++) {
       runningMax = Math.Max(runningMax, values[i]);
    }
    return runningMax;
}

Solution 8 - C#

Maximum element value in priceValues[] is maxPriceValues :

double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();

Solution 9 - C#

You could try this code:

private float GetBrightestColor(float r, float g, float b) { 
	if (r > g && r > b) {
		return r;
	} else if (g > r && g > b) { 
		return g;
	} else if (b > r && b > g) { 
		return b;
	}
}

Solution 10 - C#

This function takes an array of integers. (I completely understand @Jon Skeet's complaint about sending arrays.)

It's probably a bit overkill.

    public static int GetMax(int[] array) // must be a array of ints
    {
        int current_greatest_value = array[0]; // initializes it
    
        for (int i = 1; i <= array.Length; i++)
        {
            // compare current number against next number
    
            if (i+1 <= array.Length-1) // prevent "index outside bounds of array" error below with array[i+1]
            {
                // array[i+1] exists
                if (array[i] < array[i+1] || array[i] <= current_greatest_value)
                {
                    // current val is less than next, and less than the current greatest val, so go to next iteration
                    continue;
                }
            } else
            {
                // array[i+1] doesn't exist, we are at the last element
                if (array[i] > current_greatest_value)
                {
                    // current iteration val is greater than current_greatest_value
                    current_greatest_value = array[i];
                }
                break; // next for loop i index will be invalid
            }
    
            // if it gets here, current val is greater than next, so for now assign that value to greatest_value
            current_greatest_value = array[i];
        }
    
        return current_greatest_value;
    }

Then call the function :

int highest_val = GetMax (new[] { 1,6,2,72727275,2323});

// highest_val = 72727275

Solution 11 - C#

If you don't want to repeatedly calling the Max function, can do like this

new List<int>() { A, B, C, D, X, Y, Z }.Max()

Solution 12 - C#

in case you need sorting as well:

var side = new double[] {5,3,4}
Array.Sort(side);

//side[2] is a maximum

Solution 13 - C#

You can use if and else if method for three values but it would be much easier if you call call twice Math.Max method like this

        Console.WriteLine("Largest of three: " + Math.Max(num1, Math.Max(num2, num3)));
        Console.WriteLine("Lowest of three: " + Math.Min(num1, Math.Min(num2, num3)));

       
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJamesRedcoatView Question on Stackoverflow
Solution 1 - C#Andrew HareView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#BasView Answer on Stackoverflow
Solution 4 - C#Herman SchoenfeldView Answer on Stackoverflow
Solution 5 - C#user384080View Answer on Stackoverflow
Solution 6 - C#BerialView Answer on Stackoverflow
Solution 7 - C#strayaView Answer on Stackoverflow
Solution 8 - C#Bo JanglesView Answer on Stackoverflow
Solution 9 - C#Mark AvenView Answer on Stackoverflow
Solution 10 - C#user11777932View Answer on Stackoverflow
Solution 11 - C#TPGView Answer on Stackoverflow
Solution 12 - C#DanilView Answer on Stackoverflow
Solution 13 - C#Koshila SandaruView Answer on Stackoverflow