Home Linq - *By Operators
Post
Cancel

Linq - *By Operators

.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

TSource? MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

MaxBy

TSource? MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

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

IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

DistinctBy as the name suggests will return only the distinct elements from two IEnumerable collections, by using a property as a key selector.

ExceptBy

IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector);

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

IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelector);

Differently from ExceptBy, IntersectBy will bring only the elements that exist on the two IEnumerable collections you’re intersecting by.

UnionBy

IEnumerable<TSource> UnionBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector);

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.


Check the project on GitHub



This post is licensed under CC BY 4.0 by the author.