Skip to content

[API Proposal]: EqualityComparer.Create from selecting a key property #115797

Open
@weitzhandler

Description

@weitzhandler

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

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions