Table of Contents

Class DynamicComparer

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

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

public static class DynamicComparer
Inheritance
DynamicComparer

Examples

The following example shows how to create custom IComparer<T> instances using DynamicComparer with lambda expressions. It demonstrates sorting by string length and in descending order, printing each sorted array.

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

namespace MyApp.Examples;

public static class DynamicComparerExample
{
    public static void Demonstrate()
    {
        string[] fruits = ["apple", "pear", "banana", "kiwi"];

        // Create a dynamic comparer that sorts by string length
        IComparer<string> lengthComparer = DynamicComparer.Create<string>((x, y) =>
            x.Length.CompareTo(y.Length));

        Array.Sort(fruits, lengthComparer);
        Console.WriteLine(string.Join(", ", fruits));

        // Create a comparer that sorts descending
        IComparer<string> descendingComparer = DynamicComparer.Create<string>((x, y) =>
            string.Compare(y, x, StringComparison.Ordinal));

        Array.Sort(fruits, descendingComparer);
        Console.WriteLine(string.Join(", ", fruits));
    }
}

Methods

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

Creates a dynamic instance of an IComparer<T> implementation wrapping Compare(T, T) through comparer.

public static IComparer<T> Create<T>(Func<T, T, int> comparer)

Parameters

comparer Func<T, T, int>

The function delegate that performs a comparison of two objects of the same type and returns a value indicating whether one object is less than, equal to, or greater than the other.

Returns

IComparer<T>

A dynamic instance of IComparer<T> that serves as a sort order comparer for type T.

Type Parameters

T

The type of objects to compare.