Skip to content

IEqualityComparer for sequences (T[], Memory<T>, IEnumerable<T>) #44796

Open
@GSPP

Description

@GSPP

Problem:

Sometimes, it is useful to use arrays as keys in a map such as Dictionary. A motivating use case would be blockchain applications. Here, we often need to map a hash to some piece of data. For example, we might want to map a 32 byte block hash (byte[]) to block metadata.

Proposal:

There should be built-in equality comparers for sequences. By default, each element is default-compared. It should be possible to use a custom nested comparer.

I propose this API surface:

public static class EqualityComparer
{
    public static IEqualityComparer<T[]> Array<T>(IEqualityComparer<T> elementComparer = null);
    public static IEqualityComparer<Memory<T>> Memory<T>(IEqualityComparer<T> elementComparer = null);
    public static IEqualityComparer<IEnumerable<T>> Sequence<T>(IEqualityComparer<T> elementComparer = null);
}

Example usage:

var dict = new Dictionary<byte[], BlockHeader>(EqualityComparer.Array<byte>());

These factory methods can internally pick an optimal comparer for the given arguments. For example, for arrays of primitive types, we can use memcmp-style algorithms internally. If a custom comparer is provided, an element-by-element comparison algorithm must be used. A cached instance can be used if no custom comparer is provided.

Possible extension: The same thing could be done for IComparer<T[]> (see #33873).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions