2012-06-13 2 views
1

공통적 인 내재 성을 공유하지 않는 다른 유형의 다른 목록 요소와 비교 될 수있는 목록의 모든 요소를 ​​제거하려고합니다. 에 대한 평등 함수가 있어야합니다. 예는 명확하게 있습니다요소가 다른 유형의 두 목록의 상대적인 보완

bool isSomeSortOfEqual(Bottle b, Printer p){ 
    //implementation 
} 

List<Bottle> bottles = getBottles(); 
List<Printer> printers = getPrinters(); 

내가 이런 일을 수행하고자하는 발판 주어진

:

List<Bottle> result = bottles.Except(printers, (b, p => isSomeSortOfEqual(b, p)); 

은 .NET에서이에 대한 모든 내장 명령이 있습니까를, 또는 내가해야 손으로 이것을 구현합니까? 상대 보완 또는 .NET에서 stackoverflow 제외하고 관련된 질문을 다른 유형의 처리하는 것 같습니다.

답변

1

어때? 기본적인 아이디어는 List<object>에 목록을 캐스팅 한 다음 IEqualityComparer<object>

class A 
    { 
     public int Ai; 
    } 
    class B 
    { 
     public int Bi; 
    } 

    public class ABComparer : IEqualityComparer<object> 
    { 
     public bool Equals(object x, object y) 
     { 
      A isA = x as A ?? y as A; 
      B isB = x as B ?? y as B; 

      if (isA == null || isB == null) 
       return false; 

      return isA.Ai == isB.Bi; 
     } 

     public int GetHashCode(object obj) 
     { 
      A isA = obj as A; 
      if (isA != null) 
       return isA.Ai; 

      B isB = obj as B; 
      if (isB != null) 
       return isB.Bi; 

      return obj.GetHashCode(); 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<object> As = new List<object> { new A { Ai = 1 }, new A { Ai = 2 }, new A { Ai = 3 } }; 
      List<object> Bs = new List<object> { new B { Bi = 1 }, new B { Bi = 1 } }; 

      var except = As.Except(Bs, new ABComparer()).ToArray(); 
      // Will give two As with Ai = 2 and Ai = 3 
     } 
    } 
+0

현실 세계 시나리오에서 어려운 부분은 좋은 해시 함수를 제안하는 것입니다. – Henrik

+0

이 경우 그렇지 않습니다. 두 클래스 모두 동일한 실제 개체를 설명하며이 코드는 두 개체 사이에 몇 가지 접착제를 포함합니다. 나는 둘 중 하나의 내부에 접근 할 수 없으며, 어떤 공통적 인 ancester도 공유하지 않는다. – Martijn

1

되지 않은 경기와 .Except을 사용하는 것입니다?

from b in bottles 
where !printers.Any(p => isSomeSortOfEqual(b, p)) 
select b; 
관련 문제