문제

나는 이것을 가지고있다

 var n = ItemList.Select(s => new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList();
 n.AddRange(OtherList.Select(s => new { s.Vchr, s.Id, s.Ctr, s.Vendor, s.Description, s.Invoice }).ToList(););

허용 된 경우 이렇게하고 싶습니다.

n = n.Distinct((x, y) => x.Vchr == y.Vchr)).ToList();

제네릭을 사용해 보았습니다 Lambdacomparer 그러나 익명 유형을 사용하는 IM이기 때문에 유형이 연결되지 않습니다.

"오비 완 케노비를 도와주세요, 당신은 나의 유일한 희망"

도움이 되었습니까?

해결책

트릭은 추론 된 유형에서만 작동하는 비교를 만드는 것입니다. 예를 들어:

public class Comparer<T> : IComparer<T> {
  private Func<T,T,int> _func;
  public Comparer(Func<T,T,int> func) {
    _func = func;
  }
  public int Compare(T x,  T y ) {
    return _func(x,y);
  }
}

public static class Comparer {
  public static Comparer<T> Create<T>(Func<T,T,int> func){ 
    return new Comparer<T>(func);
  }
  public static Comparer<T> CreateComparerForElements<T>(this IEnumerable<T> enumerable, Func<T,T,int> func) {
    return new Comparer<T>(func);
  }
}

이제 다음을 수행 할 수 있습니다 ... 해킹 솔루션 :

var comp = n.CreateComparerForElements((x, y) => x.Vchr == y.Vchr);

다른 팁

대부분의 경우 (평등 또는 분류) 비교할 때 평등 또는 비교 방법 자체가 아니라 비교할 키를 선택하는 데 관심이 있습니다 (Python의 목록 정렬 API의 아이디어입니다).

주요 평등 비교의 예가 있습니다 여기.

Jaredpar의 답변은 구별되는 세트 방법이 필요하기 때문에 질문에 대답하지 않습니다. IEqualityComparer<T> 아닙니다 IComparer<T>. 다음은 iquateable이 적합한 gethashcode를 가질 것이라고 가정하며, 확실히 적합한 동등한 방법을 가지고 있습니다.

public class GeneralComparer<T, TEquatable> : IEqualityComparer<T>
{
    private readonly Func<T, IEquatable<TEquatable>> equatableSelector;

    public GeneralComparer(Func<T, IEquatable<TEquatable>> equatableSelector)
    {
        this.equatableSelector = equatableSelector;
    }

    public bool Equals(T x, T y)
    {
        return equatableSelector.Invoke(x).Equals(equatableSelector.Invoke(y));
    }

    public int GetHashCode(T x)
    {
        return equatableSelector(x).GetHashCode();
    }
}

public static class GeneralComparer
{
    public static GeneralComparer<T, TEquatable> Create<T, TEquatable>(Func<T, TEquatable> equatableSelector)
    {
        return new GeneralComparer<T, TEquatable>(equatableSelector);
    }
}

정적 클래스 트릭에서 동일한 추론이 Jaredpar의 답변에서 사용되는 경우.

더 일반적으로 두 가지를 제공 할 수 있습니다 FuncS : a Func<T, T, bool> 평등을 확인하고 Func<T, T, int> 해시 코드를 선택합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top