This post will discuss how to find an object with a minimum or maximum property value in C#.

1. Using MinBy() and MaxBy() method

You can get an object with minimum and maximum value of a specific property in linear time using LINQ’s MinBy() and MaxBy() methods. The MinBy() and MaxBy() methods return the minimum and the maximum value in a sequence, respectively, according to the provided key selector function and key comparer. The following example provides a simple illustration:

Download  Run Code

 
Note that both MinBy() and MaxBy() methods are included with LINQ and requires System.Linq namespace. If you don’t want to use LINQ, you can find the object with minimum/maximum value by traversing the sequence using a for-loop, and comparing each encountered item with the minimum/maximum value found so far.

2. Using Aggregate() method

LINQ’s Aggregate() function is used to apply an accumulator function to each element of a sequence. You can use it as follows to find a Person object with minimum and maximum Age in an array/list:

Download  Run Code

3. Using Sorting (Not Recommended)

Another approach is to sort the sequence based on the required attribute and select the first item in the sorted sequence as the object with minimum value and the last item in the sorted sequence as the object with maximum value. This approach is not recommended as sorting takes O(n.log(n)) time.

Download  Run Code

That’s all about finding the object with minimum or maximum property value in C#.