HomeSearch | ## C# Max and Min: Get Highest or Lowest ElementUse Max and Min from System.Linq. Get the highest or lowest elements. | |

## Max, Min.In the city skyline we see the highest tower. In C# we call Max (and Min) from System.Linq to get the largest or smallest element. Each element is iterated in the search. | ||

## These methodscan also be used with lambda expressions. The result of the lambda is used. Higher-order functions can make programs shorter (but sometimes slower and harder to read).Lambdas | ||

## Max.This program instantiates an array of 4 integers on the heap. Next the Max method is called upon this array. Finally we use another version of Max that receives a lambda expression.
| C# 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 | |

## Min.We want to find the minimum value in a collection (such as an array or List) in a simple way. With Min() we find the minimum element or the minimum value after a transformation.ArrayList
| 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 | |

## Notes, above program.The first call to Min determines that -1 is the smallest integer. The second call changes the 2 to -2, so that is now the smallest integer.
| ||

## A summary.The Max function can find either the maximum value in a collection, or the maximum value after a specific transformation is applied. Min returns the minimum value. | ||

## Notes.These methods are perhaps most useful with a lambda expression: this makes the computation adjustable. Other forms of delegates (not just lambdas) can be used. | ||

Home Dot Net Perls | © 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com. |