2014-01-10 2 views
0

두 목록에있는 개체를 비교할 방법을 찾고 있습니다. 목록에있는 객체는 두 가지 유형이지만 키 - 값을 공유합니다. 예 :linq을 사용하여 두 가지 유형의 두 목록을 비교하십시오.

public class A 
{ 
    public string PropA1 {get;set;} 
    public string PropA2 {get;set;} 
    public string Key {get;set;} 
} 

public class B 
{ 
    public string PropB1 {get;set;} 
    public string PropB2 {get;set;} 
    public string Key {get;set;} 
} 

var listA = new List<A>(...); 
var listB = new List<B>(...); 

키 넣은 사람은 아니다는 listB에 존재하는 A 형의 객체의 목록을 얻을 수있는 가장 빠른 방법은 무엇입니까 , 키가 중고 장비 구매에 존재하지 않는 B 형의 객체의 목록, 일치하는 키가있는 객체의 조인 된 목록? Linq를 사용하여 가입 목록을 만들었습니다.

var joinedList = listA.Join(listB, 
    outerkey => outerkey.Key, 
    innerkey => innerkey.Key, 
    (a, b) => new C 
    { 
     A = a, 
     B = b 
    }).ToList(); 

하지만 일치하는 개체 만 포함되어 있습니다. 다른 목록을 얻을 수있는 방법이 있습니까? 반대를하는

var hashSet = new HashSet<String>(bList.Select(x => x.Key)); 
var diff = aList.Where(x => !hashSet.Contains(x.Key)); 

다음 목록을 전환하는 것만 큼 쉽습니다로 B의 키를 가지고 있지 않는 세트를 얻기

답변

8

수행 할 수 있습니다. 또는 다음과 같은 함수로이를 추상화 할 수 있습니다.

IEnumerable<T1> Diff<T1, T2>(
    IEnumerable<T1> source, 
    IEnumerable<T2> test, 
    Func<T1, string> getSourceKey, 
    Func<T2, string> getTestKey) { 

    var hashSet = new HashSet<string>(test.Select(getTestKey)); 
    return source.Where(x => !hashSet.Contains(getSourceKey(x)); 
} 

// A where not key in B 
Diff(aList, bList, a => a.Key, b => b.Key); 

// B where not key in A 
Diff(bList, aList, b => b.Key, a => a.Key); 
+0

내가 원하는 것! – Pbirkoff

관련 문제