简体   繁体   中英

compare two lists of differtent types using linq

I'm looking for a way to compare the objects in two lists. The objects in the list are of two different types, but share a key-value. eg

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>(...);

What is the quickest way to get a list of objects of type A, where the key doens't exist in listB, a list of objects of type B, where the key doesn't exist in listA, and a joined list of objects with matching keys? I've managed to create the joined list using Linq:

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

but this only contains matching objects ofcourse. Is there a way to get the other lists?

Getting the set of A which doesn't have a key in B can be done as follows

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

Doing the opposite is as easy as switching the lists. Or we could just abstract this out to a function as follows

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM