In data processing scenarios, a certain object with a minimum or maximum value with a specific attribute is often required. Linq provides simple methods to achieve this.
Let's review your example, where the Person object has the dateofbirth attribute that can be empty. To find the earliest people in the birth date, you first tried the following methods:
But this will only retrieve the smallest Dateofbirth value. To retrieve the corresponding Person object, additional query is still required.
<code>var firstBornDate = People.Min(p => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue));</code>
Simple solution: Use Aggregate
Linq provides an alternative method to use the Aggregate method:
This code fragment can be used to retrieve the smallest Dateofbirth value and the corresponding Person object in a single query. It iteratively compares the DATEOFBIRTH property of each element with the current minimum value and returns elements with the minimum value.
<code>var firstBorn = People.Aggregate((curMin, x) => (curMin == null || (x.DateOfBirth ?? DateTime.MaxValue) < (curMin.DateOfBirth ?? DateTime.MaxValue)) ? x : curMin);</code>
The above is the detailed content of How Can LINQ Efficiently Find the Object with the Minimum or Maximum Property Value?. For more information, please follow other related articles on the PHP Chinese website!