# Second maximum number

How to find out second maximum number in C#?

#### Werty

• Nov 10th, 2013

For example.

```Codeint[] t = new int[5];
int max= 0,max2=0;
Random rnd = new Random();
for (int i = 0; i < t.Length; i++)
{
t[i] = rnd.Next(10);
}
for (int i = 0; i < t.Length; i++)
{
Console.WriteLine(t[i]);
}
for (int i = 0; i < t.Length; i++)
{
if (max < t[i])
max = t[i];
}
for (int i = 0; i < t.Length; i++)
{
if (t[i] != max && t[i] > max2)
max2 = t[i];
}
Console.WriteLine("max2="+max2);```

#### Deepak

• Mar 11th, 2015

Use LINQ

#### Vasyliy Zvarydchuk Profile Answers by Vasyliy Zvarydchuk

• Sep 5th, 2015

```Code
var array = new[] { 3, 1, 4, 8 };
Array.Sort(array);
if (array.Length - 2 >= 0)
{
var secondMax = array[array.Length - 2];
}
```

#### Vasyliy Zvarydchuk Profile Answers by Vasyliy Zvarydchuk

• Oct 28th, 2015

This code will work even if array will have a few maximums. Ex: (10, 8, 8, -2, 4, 10, 1)

```Codestatic int GetSecondMax(int[] array)
{
if(array.Length < 2)
throw new ArgumentException("array has to have at least 2 elements");
Array.Sort(array);
var max = array[array.Length - 1];
for (var i = 1; i < array.Length; i++)
{
var secondMax = array[array.Length - 1 - i];
if (secondMax != max)
return secondMax;
}
// array has all the same elements. In this case we
return max;
}```

#### Roger Hyde

• Feb 6th, 2016

Linq makes this quite simple

```Codeint GetSecondMax(int[] numbers)
{
return numbers.Distinct().OrderByDescending(n => n).Skip(1).Take(1).FirstOrDefault();
}```