UFO ET IT

IComparer 인수 대신 람다 식 사용

ufoet 2020. 12. 15. 19:35
반응형

IComparer 인수 대신 람다 식 사용


C #을 사용하여 메서드 호출에서 람다 식을 IComparer 인수로 전달할 수 있습니까?

예 : 뭔가

var x = someIEnumerable.OrderBy(aClass e => e.someProperty, 
(aClass x, aClass y) => 
  x.someProperty > y.SomeProperty ?  1 : x.someProperty < y.SomeProperty ?  -1 : 0);

나는 이것을 컴파일 할 수 없으므로 추측하지 못하지만 람다와 익명 델리게이트 사이의 명백한 시너지 효과로 보이며 어리석은 일을 잘못하고 있다고 생각합니다.

TIA


Jeppe가 지적했듯이 .NET 4.5를 사용하는 경우 정적 메서드를 사용할 수 있습니다 Comparer<T>.Create.

그렇지 않은 경우 이는 동일해야하는 구현입니다.

public class FunctionalComparer<T> : IComparer<T>
{
    private Func<T, T, int> comparer;
    public FunctionalComparer(Func<T, T, int> comparer)
    {
        this.comparer = comparer;
    }
    public static IComparer<T> Create(Func<T, T, int> comparer)
    {
        return new FunctionalComparer<T>(comparer);
    }
    public int Compare(T x, T y)
    {
        return comparer(x, y);
    }
}

.NET 4.5를 사용하는 경우 정적 메서드를 사용할 수 있습니다 Comparer<aClass>.Create.

문서 : Comparer<T>.Create방법 .

예:

var x = someIEnumerable.OrderBy(e => e.someProperty, 
    Comparer<aClass>.Create((x, y) => x.someProperty > y.SomeProperty ?  1 : x.someProperty < y.SomeProperty ?  -1 : 0)
    );

프로젝션 된 키 (예 : 단일 속성)를 일관되게 비교하려는 경우 null 검사, 두 개체에 대한 키 추출 및 지정된 또는 기본 내부를 사용하는 키 비교를 포함하여 모든 키 비교 논리를 캡슐화하는 클래스를 정의 할 수 있습니다. 비교 자 :

public class KeyComparer<TSource, TKey> : Comparer<TSource>
{
    private readonly Func<TSource, TKey> _keySelector;
    private readonly IComparer<TKey> _innerComparer;

    public KeyComparer(
        Func<TSource, TKey> keySelector, 
        IComparer<TKey> innerComparer = null)
    {
        _keySelector = keySelector;
        _innerComparer = innerComparer ?? Comparer<TKey>.Default;
    }

    public override int Compare(TSource x, TSource y)
    {
        if (object.ReferenceEquals(x, y))
            return 0;
        if (x == null)
            return -1;
        if (y == null)
            return 1;

        TKey xKey = _keySelector(x);
        TKey yKey = _keySelector(y);
        return _innerComparer.Compare(xKey, yKey);
    }
}

편의를 위해 공장 방법 :

public static class KeyComparer
{
    public static KeyComparer<TSource, TKey> Create<TSource, TKey>(
        Func<TSource, TKey> keySelector, 
        IComparer<TKey> innerComparer = null)
    {
        return new KeyComparer<TSource, TKey>(keySelector, innerComparer);
    }
}

그런 다음 다음과 같이 사용할 수 있습니다.

var sortedSet = new SortedSet<MyClass>(KeyComparer.Create((MyClass o) => o.MyProperty));

이 구현에 대한 자세한 설명은 블로그 게시물참조하십시오 .

참조 URL : https://stackoverflow.com/questions/16839479/using-lambda-expression-in-place-of-icomparer-argument

반응형