Table of Contents

Class DynamicEqualityComparer

Namespace
Cuemon.Collections.Generic
Assembly
Cuemon.Core.dll

Provides a factory based way to create and wrap an IEqualityComparer<T> implementation.

public static class DynamicEqualityComparer
Inheritance
DynamicEqualityComparer

Examples

The following example shows how to create a case-insensitive IEqualityComparer<string> using DynamicEqualityComparer with lambda expressions. It filters distinct values from a mixed-case word list and prints the result.

using System;
using System.Collections.Generic;
using System.Linq;
using Cuemon.Collections.Generic;

namespace MyApp.Examples;

public static class DynamicEqualityComparerExample
{
    public static void Demonstrate()
    {
        string[] words = ["Hello", "world", "hello", "World", "HELLO"];

        // Create a case-insensitive equality comparer for strings
        IEqualityComparer<string> caseInsensitive = DynamicEqualityComparer.Create<string>(
            hashCalculator: s => StringComparer.OrdinalIgnoreCase.GetHashCode(s),
            equalityComparer: (x, y) => string.Equals(x, y, StringComparison.OrdinalIgnoreCase));

        string[] distinct = words.Distinct(caseInsensitive).ToArray();
        Console.WriteLine(string.Join(", ", distinct));
    }
}

Methods

Create<T>(Func<T, int>, Func<T, T, bool>)

Creates a dynamic instance of an IEqualityComparer<T> implementation wrapping GetHashCode(T) through hashCalculator and Equals(T, T). through equalityComparer.

public static IEqualityComparer<T> Create<T>(Func<T, int> hashCalculator, Func<T, T, bool> equalityComparer)

Parameters

hashCalculator Func<T, int>

The function delegate that calculates a hash code of the specified object and is invoked first.

equalityComparer Func<T, T, bool>

The function delegate that determines whether the specified objects are equal. This delegate is invoked second if qualified.

Returns

IEqualityComparer<T>

A dynamic instance of IEqualityComparer<T> for type T.

Type Parameters

T

The type of objects to compare.

Remarks

The function delegate, hashCalculator (GetHashCode(T)), is evaluated with a conditional-AND before the second function delegate, equalityComparer (Equals(T, T)), is ivoked.