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:
![MaxBy in .NET 6+ allows us to find the item with the max value for a particular property in a collection](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKjJuuVJXuD9Nn8Yd40b5p_1wL7Icj2Ds5UfnBGua5I3lbWWyskQB9-8p8bFVmX_zSMRpLeEliZgIHBjhLwUIJ9ITEg_BpMdnZC89uc0S4cARBNf5KwynPRqwLpY0zykoASawDTQBW7TsxEX5tGfcRMo8X0A9PcRIiof3RdX_r1jF5R6m0_oK5RV_id3PZ/s72-c/4.png)