Wobbles
Wobbles

Reputation: 3135

Return from list the double value that has the highest absolute value, without making the return value absolute

Short of iterating the collection, is there a way to return the double in a set that has the highest absolute value without making the values in the set actually absolute?

double[] vals = new double[] { 2.3, 1.7, -3.8};

vals.Max(v => Math.Abs(v)); // This returns 3.8 instead of -3.8

Upvotes: 4

Views: 1102

Answers (2)

mjwills
mjwills

Reputation: 23864

One approach to consider:

var max = vals
    .OrderByDescending(z => Math.Abs(z))
    .FirstOrDefault();

Alternatively, consider using MoreLinq's MaxBy. It is faster than both my and Samvel's solution, especially for larger sets of inputs.

var max = vals.MaxBy(z => Math.Abs(z));

Upvotes: 7

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

Here are two ways of doing this:

First with LINQ:

double[] vals = new double[] { 2.3, 1.7, -3.8};
var max = vals.Max(x => Math.Abs(x)); 
Console.WriteLine(vals.Where(z => Math.Abs(z) == max).First());

Second with For loop:

int index =0;
for(int i=0;i<vals.Length;i++)
{
    if(Math.Abs(vals[i])>=Math.Abs(vals[index]))
        index=i;
}
Console.WriteLine(vals[index]); 

Upvotes: 1

Related Questions