Repository navigation
Description
I propose to add LINQ methods of the pattern *By. For example:
IEnumerable<TSource> DistinctBy<TSource, TKey>(
IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer = null)This method would behave like Distinct except that equality is determined based on the key provided by keySelector. The key could be any value including anonymous types and value tuples.
A motivating case could be this:
IEnumerable<Order> allOrders = GetTransactions();
IEnumerable<int> completedOrderIDs = GetCompletedOrderIDs();
IEnumerable<Order> remainingOrders =
allOrders.ExceptBy(completedOrderIDs, order => order.ID, orderID => orderID);Logic like that is reasonably common in business logic code. It is not easy to implement without ExceptBy. In particular, the following is undesirable because it leads to quadratic cost and repeated enumeration:
IEnumerable<Order> remainingOrders = allOrders.Where(o => !completedOrderIDs.Contains(o.ID));In the past I have had a need for *By methods many times so I have written them myself. A web search reveals great interest. I believe there is a strong case for adding methods like this.
There has been interest on this issue tracker as well:
- Feature Request: Overload for Distinct to receive a func. dotnet/runtime#27665
- Consider adding more LINQ operators from Ix.NET dotnet/runtime#19522
- Add commonly required Enumerable methods (DistinctBy, ExceptBy, AsChunked, ...) dotnet/runtime#14753
Proposed API
@eiriktsarpalis has provided the following shape for API review. Please refer to my original proposal below for reference.
namespace System.Linq
{
public static class Enumerable
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer);
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector);
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer);
public static IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector);
public static IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer);
public static IEnumerable<TSource> UnionBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector);
public static IEnumerable<TSource> UnionBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer);
public static TSource MinBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
public static TSource MinBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult>? comparer);
public static TSource MaxBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
public static TSource MaxBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult>? comparer);
// Missing min & max overloads accepting custom comparers added for completeness
public static TResult Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult>? comparer);
public static TResult Max<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult>? comparer);
}
}and equivalent Queryable APIs:
namespace System.Linq
{
public static class Queryable
{
public static IQueryable<TSource> DistinctBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector);
public static IQueryable<TSource> DistinctBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IEqualityComparer<TKey>? comparer);
public static IQueryable<TSource> ExceptBy<TSource, TKey>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, Expression<Func<TSource, TKey>> keySelector);
public static IQueryable<TSource> ExceptBy<TSource, TKey>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, Expression<Func<TSource, TKey>> keySelector, IEqualityComparer<TKey>? comparer);
public static IQueryable<TSource> IntersectBy<TSource, TKey>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, Expression<Func<TSource, TKey>> keySelector);
public static IQueryable<TSource> IntersectBy<TSource, TKey>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, Expression<Func<TSource, TKey>> keySelector, IEqualityComparer<TKey>? comparer);
public static IQueryable<TSource> UnionBy<TSource, TKey>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, Expression<Func<TSource, TKey>> keySelector);
public static IQueryable<TSource> UnionBy<TSource, TKey>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, Expression<Func<TSource, TKey>> keySelector, IEqualityComparer<TKey>? comparer);
public static TSource MinBy<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector);
public static TSource MinBy<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, IComparer<TResult>? comparer);
public static TSource MaxBy<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector);
public static TSource MaxBy<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, IComparer<TResult>? comparer);
// Missing min & max overloads accepting custom comparers added for completeness
public static TResult Min<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, IComparer<TResult>? comparer);
public static TResult Max<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, IComparer<TResult>? comparer);
}
}EDIT @eiriktsarpalis: the key change in this amendment is that the ExceptBy and IntersectBy overloads do not allow heterogeneous element types for the second parameter. This makes it less of a join-like construct and more compatible with both the existing Except and Intersect methods as well as the proposed signature for UnionBy. Please follow the conversation after this comment for more details on the issue.
Open Questions
- The
ExceptByandIntersectBymethods can be generalized by admitting heterogeneous element types in thesecondparameter. This enables applications like the one cited in the first example, at the cost of requiring a separatekeySelectorargument for the second collection. Note that this generalization is not admissible in theUnionBycase. - Should the
*Bymethods accept custom comparers for the key types in addition to key selector lambdas? While there is certainly precedent for similar methods in LINQ, there is also an element of over-engineering here: the natural equality/ordering semantics of ad-hoc key projections are almost always sufficient. YAGNI.
Original API Proposal
Here is the API proposal. All of these methods come with an overload with and without comparer. I kept the existing naming conventions and argument ordering.
namespace System.Linq
{
public static class Enumerable
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer);
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelectorFirst);
public static IEnumerable<TSource1> ExceptBy<TSource1, TSource2, TKey>(this IEnumerable<TSource1> first, IEnumerable<TSource2> second, Func<TSource1, TKey> keySelectorFirst, Func<TSource2, TKey> keySelectorSecond);
public static IEnumerable<TSource1> ExceptBy<TSource1, TSource2, TKey>(this IEnumerable<TSource1> first, IEnumerable<TSource2> second, Func<TSource1, TKey> keySelectorFirst, Func<TSource2, TKey> keySelectorSecond, IEqualityComparer<TKey> comparer);
public static IEnumerable<TSource> IntersectBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TKey> second, Func<TSource, TKey> keySelectorFirst);
public static IEnumerable<TSource1> IntersectBy<TSource1, TSource2, TKey>(this IEnumerable<TSource1> first, IEnumerable<TSource2> second, Func<TSource1, TKey> keySelectorFirst, Func<TSource2, TKey> keySelectorSecond);
public static IEnumerable<TSource1> IntersectBy<TSource1, TSource2, TKey>(this IEnumerable<TSource1> first, IEnumerable<TSource2> second, Func<TSource1, TKey> keySelectorFirst, Func<TSource2, TKey> keySelectorSecond, IEqualityComparer<TKey> comparer);
public static IEnumerable<TSource> UnionBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector);
public static IEnumerable<TSource> UnionBy<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer);
public static TResult Max<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer);
public static TResult Max<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer, TResult defaultValue);
public static TSource MaxBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
public static TSource MaxBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer);
public static TSource MaxBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer, TSource defaultValue);
public static TResult Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer);
public static TResult Min<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer, TResult defaultValue);
public static TSource MinBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
public static TSource MinBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer);
public static TSource MinBy<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, IComparer<TResult> comparer, TSource defaultValue);
}
}Further notes:
DistinctBy: The order of the output elements should be documented to be the same order as the input. Any reasonable implementation that comes to mind does it this way. For compatibility reasons this could not ever be changed anyway after the first version ships.Distinctshould be similarly documented if not already done.Distinctalready behaves this way.- For
ExceptByandIntersectBythe same is true for the first input. Only items from the first input are ever returned and their order can be kept.Exceptdoes the same thing today. - For
UnionByI'm not sure about the order. - For
MinBy/MaxByit should be documented that the first element in the sequence with the minimum/maximum key is returned. MinBy/MaxBycan take adefaultValuewhich is used in case the sequence is empty. Overloads without default value throw in that case.- I added overloads to
Min/Maxto bring them on par with the functionality added byMinBy/MaxBy(compareranddefaultValue). - Note, that the input element types for
ExceptByandIntersectBycan be different. This is because we only ever return items of the first sequence. We need two key selectors in that case. There's a simpler overload that has only one element type as well.
Activity
MgSam commentedon Oct 22, 2018
Not sure why #14753 was closed way back when.
It is crazy that LINQ doesn't have these methods built in. I think it's been rare in the 10 years since LINQ's introduction that I've ever had a project where I don't end up writing one or more of these extension methods again and again myself.
I think the argument (mentioned in the other thread) of, "oh well you can do these things by creating a custom comparer" doesn't hold water. Writing a custom comparer is very heavyweight. And, in practice, I can probably count on one hand the number of times I've seen developers actually go and write their own comparers. Instead they usually a) use home-grown extension methods that do these things or b) fall back to writing a foreach loop.
One of the main points of LINQ is brevity- writing what you want to do, not all the plumbing code required to do it. Forcing users to write a separate class each time they want to slice their enumerable a different way is the absolute antithesis of this.
To implement these methods, I'd imagine it could just use something like Jon Skeet's ProjectionEqualityComparer and call the existing non-*By methods. (Probably deserves a separate issue, but that class should be exposed publicly in the framework proper as well)
omariom commentedon Jun 2, 2020
@maryamariyan
The original issue is five years old. Seven versions of .NET Core have been released since then.
These methods are extremely convenient (unlike the overloads with IEqualityComparer) and are easy to implement.
lipchev commentedon Jun 28, 2020
In an effort to unify my own *By extension methods (with the hope that those would someday would become part of the runtime) I came looking for a reference implementation that I could grab.
As far as I can tell the extrema-finding functions from both MoreLINQ and Ix.NET cause the evaluation of the selector function for single-element collections.
The decision to skip it (when possible) does come with the side effects of "hiding" a possible exception occurring in it, but at the same time- there is no "valid selector guarantee" with the empty collection either- so to me it would make sense to avoid the possibly lengthy selector evaluation (when possible)- but since the normal
Enumerable.Min(source, selector)does it as well- might be the dominating factor in the final decision...Anyway, can anybody point me to an existing implementation of the proposed API - looking through these 100+ pages of search results is quite painful (in more than one ways)- and I see no way of filtering out the "*ByTest.cs" files...
maryamariyan commentedon Jun 28, 2020
/cc: @eiriktsarpalis @adamsitnik
MgSam commentedon Aug 14, 2020
@terrajobst What needs to happen to get these API suggestions reviewed and get any official feedback from the team? I saw you mention in the standup yesterday that you guys have a clear plate now... :)
terrajobst commentedon Oct 2, 2020
The API process is documented. Each area has an owner and it's their responsibility to work with the issue opener to get the issue either into the state api-ready-for-review or closed.
In this case, that's @eiriktsarpalis and @adamsitnik.
eiriktsarpalis commentedon Dec 2, 2020
A few remarks:
MinByandMaxBy. They are useful methods without good alternatives at the moment. I'm not sure if we should add thedefaultValueoverloads.DistinctByis useful. It should also come with an IQueryable implementation.ExceptBysolve? You assert that a naive workaround would take quadratic time, however most instances I've seen would simply usecompletedOrderIDs.ToHashSet();outside of the main pipeline which is effectively equivalent.ExceptByoverloads that select keys for thesecondenumerable? Using your example it could be easily rewritten in terms of the first oveload:allOrders.ExceptBy(completedOrderIDs.Select(orderID => orderID), order => order.ID);UnionBycorrectly, is it basically usingkeySelectorto define custom a equality semantics forTSource? How is that different from passing a customIComparerto the existingUnionmethod? Why should it even have a different name?IntersectBysignatures. Am I right to assume they're just mistakenly copied from theExceptByAPIs?MgSam commentedon Dec 2, 2020
@eiriktsarpalis Is there a reason you guys haven't reviewed this (or scheduled it for review) yet? I realize it doesn't follow the template but it seems pretty clear what it's asking and obviously you guys are aware of the proposal.
thomaslevesque commentedon Dec 2, 2020
@eiriktsarpalis
It's not different in terms of behavior (I assume you meant IEqualityComparer), and the same is true of all those proposed methods (ExceptBy, UnionBy, IntersectBy, DistinctBy). But writing a custom equality comparer every time you want to perform one of those operations based on a given property is time-consuming, and the logic of the comparison isn't immediately visible without looking at the implementation. The *By overloads make the code terser and more readable.
eiriktsarpalis commentedon Dec 3, 2020
Couple of reasons. The size of the backlog is significant so it takes us time before we can get to triage everything. I also need to be confident that any proposal has a strong chance of getting approved before I mark it as ready for review: this includes gathering evidence that the addition provides value to users, poking holes in the design, and finalizing the API shape. Following the template is part of that, but that's merely a convention meant to speed up API review that frankly takes a tiny fraction of the whole effort.
I suppose my original question is should they contain the
Bysuffix at all, given that they could just be thought of as overloads that accept a key selector instead of a comparer. While most current LINQ methods accepting akeySelectordo have aBysuffix, none of them have equivalent methods that acceptIEqualityComparerinstead.GSPP commentedon Dec 9, 2020
If somebody were to step up and commit to implementing what's approved, would that be enough to take it forward? There are 56 positive votes at this point.
I'll also use this opportunity to lobby for #27449 (comment) (IEnumerable should have a extension for creating fixed size chunks) 😄
24 remaining items
MgSam commentedon Feb 4, 2021
Now that this is approved, should we make a separate issue for
IntersectByandExceptByfor heterogenous sources? I think those are also extremely useful and there's not a simple workaround to get the same functionality with existing LINQ methods.eiriktsarpalis commentedon Feb 4, 2021
We shouldn't need to, the approved API includes the following overloads which should be sufficient to address the requirement:
Clockwork-Muse commentedon Feb 4, 2021
Side question: are we going to be adding any of these to PLINQ?
MgSam commentedon Feb 4, 2021
@eiriktsarpalis That only works if the the second collection is already the type of the projection. I'd say that's less common than the case when the collections are two completely unrelated types.
Obviously this example is contrived but real-world scenarios like this happen all the time.
eiriktsarpalis commentedon Feb 4, 2021
@MgSam this should probably cover your use case:
Seems reasonable, but I would defer to @adamsitnik, @carlossanlop and @jozkee on that call. I would recommend creating a separate issue and we can revisit at a later iteration.
MgSam commentedon Feb 8, 2021
@eiriktsarpalis Great point that there is a relatively easy workaround given the new methods. I haven't wrapped my brain around having them available yet. :)
That said, these overloads that I've proposed are straightforward and useful enough to be added outright, IMO. In other parts of LINQ, (like
GroupBy<TSource,TKey,TResult>(IEnumerable<TSource>, Func<TSource,TKey>, Func<TKey,IEnumerable<TSource>,TResult>)) additional Selects are eschewed in favor of offering useful overloads that do the projection for you. Also, the newZipoverload is similarly just for convenience.C-xC-c commentedon Mar 23, 2021
I would like to work on this if possible
eiriktsarpalis commentedon Mar 24, 2021
Hi @C-xC-c, thanks for volunteering. I had actually started working on the feature a few weeks back but just didn't have enough time to see it through: eiriktsarpalis@7e37b77. Feel free to reuse any or none of that.
eiriktsarpalis commentedon Mar 28, 2021
Hi again @C-xC-c, have you begun work on the feature? I actually just finished work on my own branch so will post a PR today. Hope that's ok.
C-xC-c commentedon Mar 29, 2021
I was working on my branch locally but that's okay! Glad to see this get done!