Get maxAbs from array c# [closed]

You, probably, mean ArgMax, not Max

the element … which have the max abs value

Linq doesn’t provide such a method, but you can easily emulate it:

var result = vec.Aggregate((a, s) => Math.Abs(a) > Math.Abs(s) ? a : s);

Test:

int[] vec = new int[] { 1, -3, 2 };

var result = vec.Aggregate((a, s) => Math.Abs(a) > Math.Abs(s) ? a : s);

// The output is "-3" (the element in the array)
Console.Write(result);

Edit: if you’re looking for the array’s index, all you have to do is to modify the code a bit:

var result = vec
  .Select((value, index) => new {
      Value = value,
      Index = index })
  .Aggregate((a, s) => Math.Abs(a.Value) > Math.Abs(s.Value) ? a : s)
  .Index;

// Output: "vec[1] == -3"
Console.Write($"vec[{result}] == {vec[result]}");

Leave a Comment