.NET 6 introduces a series of new extension methods on System.Linq
namespace to ease handling IEnumerable
in many ways, such as MinBy
, MaxBy
, DistinctBy
, ExceptBy
, IntersectBy
and UnionBy
.
I’ll be focusing on the signatures without the IEqualityComparer
argument.
By the way…
MinBy
MaxBy
MinBy
and MinBy
bring very convenient ways to find the minimum and maximum elements respectively, by using a property as a key selector. Unlike the known Min
and Max
methods available till now, it does not require the element objects to implementIComparable
.
DistinctBy
DistinctBy
as the name suggests will return only the distinct elements from two IEnumerable collections, by using a property as a key selector.
ExceptBy
ExceptBy
will bring only the elements from a given IEnumerable that couldn’t be found on a second IEnumerable of the same type. Likewise the others, it uses a property as a key selector, which has to be common between the collections you’re excepting by
.
IntersectBy
Differently from ExceptBy, IntersectBy
will bring only the elements that exist on the two IEnumerable collections you’re intersecting by
.
UnionBy
UnionBy
as the name suggests unifies the elements of two given IEnumerable collections and again uses a common field as a key selector.
Hands-On
I have written an example using all these methods against a list of objects.