Open
Description
Background and motivation
In continuation of #24460 which is so useful - thanks! it would also be great if we could create an EqualityComparer<T>
from selecting which property will be used for the comparison.
API Proposal
namespace System.Collections.Generic
{
+ public static EqualityComparer<T> Create<TKey>(
+ Func<T?, TKey?> keySelector,
+ IEqualityComparer<Tkey>? keyComparer = null)
+ {
+ ArgumentNullException.ThrowIfNull(keySelector);
+
+ keyComparer ??= EqualityComparer<TKey>.Default;
+
+ return Create(
+ equals: (itemX, itemY) =>
+ keyComparer.Equals(keySelector(itemX), keySelector(itemY)),
+ getHashCode: item => keyComparer.GetHashCode(keySelector(item)!));
+ }
}
API Usage
record Item(string Path, HighlightType Highlight);
// default implementation should be compare all props
var regular = new HashSet<Item>();
// use 'Path' property to check equality and create hashcode, specifying a hash code for key
var set1 = new HashSet<Item>(EqualityComparer<Item>.Create(item => item.Path));
// use 'Path' property to check equality and create hashcode, specifying a hash code for key
var comparer = EqualityComparer<Item>.Create(item => item.Path), StringComparer.OrdinalIgnoreCase);
var set2 = new HashSet<Item>(comparer);
Alternative Designs
No response
Risks
No response