[英]compare two lists of differtent types using 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>(...);
什么是获取类型为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();
但这仅包含匹配的课程对象。 有没有办法获得其他名单?
可以通过以下步骤获取在B中没有键的A集合
var hashSet = new HashSet<String>(bList.Select(x => x.Key));
var diff = aList.Where(x => !hashSet.Contains(x.Key));
进行相反操作就像切换列表一样容易。 或者我们可以将其抽象为如下功能
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.