[英]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.