Jack Yeoh
Jack Yeoh

Reputation: 375

Finding the next biggest value in the array C#

I have an array of 5 chars and a char '4', I would like to find the next biggest value in the array which would be a '6'. How would i go about doing this?

Thanks guys

char findNextBiggestValue = '4';
char array[5] {'3','6','7','8','9'};

Upvotes: 2

Views: 1345

Answers (5)

10K35H 5H4KY4
10K35H 5H4KY4

Reputation: 1526

Try this, first sort, then filter:

char findNextBiggestValue = '4';
char array[5] {'3','6','7','8','9'};
var val = array.OrderBy(s => s).FirstOrDefault(x => x > findNextBiggestValue);

OR

var val = array.Where(x => x > findNextBiggestValue).Min();

Upvotes: 4

Enigmativity
Enigmativity

Reputation: 117057

I would do it this way:

char findNextBiggestValue = '4';
char[] array = new [] { '3','6','7','8','9'};

char min = array.Where(c => c > findNextBiggestValue).Min();

This performs faster than a sort as it will only do a single iteration over the array. LINQ's operator chaining works with .Where(...) and .Min() operations very efficiently.

This code also returns an exception if there are no elements returned by the .Where(...) operator. This is by design as a char is a value type that must have an operator and it would be a bug to return any value as a default.

The other option would be to return a char? instead and have the null value represent no return result.

In this case the code would look like this:

char? min = array.Where(c => c > findNextBiggestValue).Cast<char?>().Min();

Upvotes: 3

Triet Doan
Triet Doan

Reputation: 12085

If you don't want to sort the array, let's try this way.

    char findNextBiggestValue = '4';
    char[] array = {'3', '6', '7', '8', '9'};

    // No elemnt? Do nothing
    if (array.Length < 1)
    {
        return;
    }

    // Init it a large value
    char minValue = 'z';

    // Look for the next bigger value
    foreach (var c in array)
    {
        if (findNextBiggestValue < c && c < minValue)
        {
            minValue = c;
        }
    }

    Console.WriteLine(minValue);

Upvotes: 1

VJPPaz
VJPPaz

Reputation: 1015

You can use the FirstOrDefault extension method to achieve this:

 array.FirstOrDefault(m=> int.Parse(m.ToString()) > int.Parse(findNextBiggestValue.ToString());

Upvotes: 0

Matthew MacFarland
Matthew MacFarland

Reputation: 2729

array.FirstOrDefault(x => x > '4')

Upvotes: 0

Related Questions