-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
API proposal: Sequence comparer #33873
Comments
I couldn't figure out the best area label to add to this issue. Please help me learn by adding exactly one area label. |
I have needed this a bunch of times for equality ( |
@GSPP As proposed, this issue is only about |
It seems like a good idea to me to do both. |
This seems reasonable, but is |
@eiriktsarpalis I'd like to add more static methods to |
It would probably though need to live in |
I proposed it on |
That's a reasonable consideration, but there is the precedent of |
In the case of Really quick, taking an example API I haven't proposed but intend to, is it even possible to place it in // Usage: Comparer.Create(StringComparer.OrdinalIgnoreCase, EqualityComparer<int>.Default)
namespace System.Collections
{
public static class Comparer
{
+ public static IComparer<(T1, T2)> Create<T1, T2>(IComparer<T1> first, IComparer<T2> second);
}
}
// Usage: Comparer<???>.Create(StringComparer.OrdinalIgnoreCase, EqualityComparer<int>.Default)
namespace System.Collections.Generic
{
public static class Comparer<T>
{
+ public static IComparer<(T1, T2)> Create<T1, T2>(IComparer<T1> first, IComparer<T2> second);
}
} |
That's a good point. We could perhaps add a new static class in System.Collections.Generic that hosts the methods (e.g. something like |
Echoing #44796, do you think we should also add comparer definitions for array and memory types? |
Yes, I was thinking that anything IEnumerable would be supported by default. |
Triage: would like to see this added, however it is not clear if the non-generic |
There is no .NET API to sort sequences lexicographically. The closest thing I know of is
Enumerable.SequenceEqual
which reports elementwise equality but not order.I've implemented one-off array/enumerable comparers in enough projects that this last time I figured I should propose it.
Usage example
Proposal
It should be a generic method on a non-generic type for usability (CA1000).
If an element comparer instance is not specified,
Comparer<T>.Default
should be used for consistency with other APIs.IComparer<>
is contravariant, so the returned comparer will be usable for any sequence of reference types implementingIEnumerable<T>
.The returned comparer type should likely not be a class that also implements IEqualityComparer because GetHashCode would have to be implemented as
0
if the user-specified element comparer cannot be cast toIEqualityComparer<T>
.Draft implementation
Click to expand
The text was updated successfully, but these errors were encountered: