.NET 6 LINQ Improvements - *By

less than 1 minute read

LINQ Methods with the pattern *By

In the APIs for System.Linq.Enumerable and System.Linq.Queryable we already have overloads for:

  • Distinct
  • Execept
  • Intersect
  • Union
  • Min
  • Max

.NET 6 is adding *By counterparts that are easier to use with complex objects:

  • DistinctBy
  • ExeceptBy
  • IntersectBy
  • UnionBy
  • MinBy
  • MaxBy

Taking Max as an Example

Where before, given some simple List<Person>, and we wanted to find the age of oldest Person, we might do:

var maxAge = list.Max(x => x.Age);

But what if we wanted the whole object? Then we write slightly more complicated code:

var oldestPerson = personList.OrderByDescending(x => x.Age).First();

In .NET 6 LINQ API, this is tidied up, and we can get the whole oldest Person object from our example, by supplying a key selector:

var oldestPerson = personList.MaxBy(x => x.Age);