C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Return: The Max method returns 1 when called with no parameters. This is because 1 is the largest value in the program's array.
However: When the Math.Abs transformation is used the value 2 is returned because the absolute value of -2 is 2, and this is larger than 1.
Note: The original value is not returned. Instead the value transformed by the lambda expression is.
Math.AbsC# program that uses Max method
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array1 = { 1, -1, -2, 0 };
// Find maximum number.
Console.WriteLine(array1.Max());
// Find maximum number when all numbers are made positive.
Console.WriteLine(array1.Max(element => Math.Abs(element)));
}
}
Output
1
2
Here: This program instantiates an array of integers upon execution. Then, the Min() method is called on the array.
Finally: The Min() method is called again, but with a lambda expression that makes all values negative.
C# program that uses Min method
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array1 = { 1, -1, 2, 0 };
// Find minimum number.
Console.WriteLine(array1.Min());
// Find minimum number when all numbers are made negative.
Console.WriteLine(array1.Min(element => -element));
}
}
Output
-1
-2
Info: The values in the source array (array1) are not mutated. Min() provides a clear way to find the smallest value in a collection.
Also: You can provide a transformation function, which provides a mechanism for you to insert additional logic if needed.