简体   繁体   中英

Need to return an object with the lowest property value from List of objects

I have a list of Customers that looks like this:

var customers = new List<Customer>
{
    new Customer { Name = "John", Age = 20 },
    new Customer { Name = "Adam", Age = 30 },
    new Customer { Name = "Joi", Age = 26 }
};

What is the best way to return the object of customer with the lowest age?

This is most efficient way:

var customers = new List<Customer>
{
    new Customer { Name = "John", Age = 20 },
    new Customer { Name = "Adam", Age = 30 },
    new Customer { Name = "Joi", Age = 26 }
};

var youngest = customers.Aggregate((x, y) => x.Age < y.Age ? x : y);

That gives me:

最年轻的

Or, now with .NET 6.0:

var youngest = customers.MinBy(c => c.Age);

I believe you would achieve that by ordering objects by age first then returning the first element in the list. and you can accomplish that by adding this linq query.

Customer lowestAgeCustomer = Customers.OrderBy(c => c.Age).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM