我正在寻找一种方法来比较两个列表中的对象.列表中的对象有两种不同的类型,但共享一个键值.例如
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>(...);
Run Code Online (Sandbox Code Playgroud)
获取类型A的对象列表的最快方法是什么,其中listB中不存在键,类型为B的对象列表,其中listA中不存在键,以及带有对象的连接列表匹配键?我已设法使用Linq创建联合列表:
var joinedList = listA.Join(listB,
outerkey => outerkey.Key,
innerkey => innerkey.Key,
(a, b) => new C
{
A = a,
B = b
}).ToList();
Run Code Online (Sandbox Code Playgroud)
但这仅包含匹配的课程对象.有没有办法获得其他名单?
获得在B中没有密钥的A的集合可以如下完成
var hashSet = new HashSet<String>(bList.Select(x => x.Key));
var diff = aList.Where(x => !hashSet.Contains(x.Key));
Run Code Online (Sandbox Code Playgroud)
相反的做法就像切换列表一样简单.或者我们可以将其抽象为函数,如下所示
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);
Run Code Online (Sandbox Code Playgroud)