Home > Backend Development > C++ > How Can LINQ Efficiently Find the Object with the Minimum or Maximum Property Value?

How Can LINQ Efficiently Find the Object with the Minimum or Maximum Property Value?

Mary-Kate Olsen
Release: 2025-02-01 03:36:10
Original
839 people have browsed it

How Can LINQ Efficiently Find the Object with the Minimum or Maximum Property Value?

Objects with the minimum/maximum attribute value with Linq

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>
Copy after login

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>
Copy after login
By using Aggregate, you can eliminate the needs for the second query and significantly simplify the code. This method is particularly useful when you need to find any extreme values ​​that may have a short value attribute.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template