반응형
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
반응형
'UFO ET IT' 카테고리의 다른 글
파이썬은 if의 조건을 느리게 평가합니까? (0) | 2020.12.15 |
---|---|
MySQL 명령 줄 결과의 출력 형식을 CSV로 변경 (0) | 2020.12.15 |
Java에서 MessageFormat.format ()을 사용하여 메시지 형식 지정 (0) | 2020.12.15 |
OpenCV detectMultiScale () 매개 변수에 대한 권장 값 (0) | 2020.12.15 |
각 비트에 대해 주어진 확률이 0 또는 1 인 의사 랜덤 비트를 생성하는 빠른 방법 (0) | 2020.12.15 |