and
methods in linq can be used to find objects with the minimum or maximum specific attribute value. However, when processing can be empty, some additional considerations may occur. Min()
Max()
The person who determines the earliest birth date
Suppose you have a list of Person objects, which contains a attribute that can be empty. You want to use Linq to find the earliest birth date.
One method is to use the DateOfBirth
method to obtain the smallest
Min()
DateOfBirth
But this will only provide the date itself. If you want the corresponding Person object, you can perform another query:
var firstBornDate = People.Min(p => p.DateOfBirth.GetValueOrDefault(DateTime.MaxValue));
<高> More efficient solutions
var firstBorn = People.Single(p => (p.DateOfBirth ?? DateTime.MaxValue) == firstBornDate);
Instead of using two queries, it is better to use the method to combine the operation:
This code iteration collection is stored in Aggregate()
. When encountering the earlier Person object, it will replace the current minimum value. As a result, Person object with the earliest birth date.
The above is the detailed content of How Can I Efficiently Find the Person with the Earliest Birth Date Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!