MaxBy in .NET 6+ allows us to find the item with the max value for a particular property in a collection
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { List<Employee> employees = new() { new Employee () { Name = "David", HoursPerweek = 40 }, new Employee () { Name = "Patrick", HoursPerweek = 35 }, new Employee () { Name = "Michelle", HoursPerweek = 60 }, new Employee () { Name = "Julie", HoursPerweek = 50 } }; // new MaxBy in .Net 6+ var longestHoursDotnet6 = employees.MaxBy(p => p.HoursPerweek); Console.WriteLine(longestHoursDotnet6?.Name); // One example might use currently... var longestHours = employees.OrderByDescending(p => p.HoursPerweek).FirstOrDefault(); Console.WriteLine(longestHours?.Name); } } public class Employee { public string Name { get; set; } public int HoursPerweek { get; set; } }
MaxBy in .NET 6+ allows us to find the item with the max value for a particular property in a collection
Reviewed by Bhaumik Patel
on
3:56 AM
Rating: