2016-04-26 40 views
2

我有相同的類型和型號的兩個列表低於:一個列表的拷貝複製到另一個使用LINQ

public string Id {get; set;} 
public string Name {get; set;} 
public string Value {get; set;} 

第一個列表 - 利斯塔是需要被複制到第二個名單是什麼 - 數組listB我們找到Id匹配

我已經實現了一個比較器,它只檢查Id,然後做一個相交來找到重複。

public bool Equals(Model x, Model y) 
    { 
     //Check whether the objects are the same object. 
     if (Object.ReferenceEquals(x, y)) return true; 

     return x != null && y != null && x.Id.Equals(y.Id); 
    } 

    public int GetHashCode(Model obj) 
    { 
     //Get hash code for the Name field if it is not null. 
     int hashProductName = obj.Id == null ? 0 : obj.Id.GetHashCode(); 

     //Calculate the hash code for the product. 
     return hashProductName; 
    } 

現在做相交:

IEnumerable<Model> duplicates = listA.Choices.Intersect(listB.Choices, new ModelComparer()); 

我想知道這是做的正確方法?

+0

你想確定哪些元素對於兩組是共同的嗎?列表中是否有重複項? – usr

+0

我們想要的唯一通用元素是Id(id始終是唯一的);至於Id匹配,我們正在尋找覆蓋整個對象。可能有ListA有3個對象,而ListB只有1的情況。我們只需要找到1,然後從ListA中更新它。 – user1932923

回答

2

有兩種主要方法可以做到這一點。我會做listB left join listA。然後,您可以處理加入的設置並返回itemFromA ?? itemFromB。這很乾淨。

另一種方法是首先使用listA.Intersect(listB)來計算交點。參數的順序非常重要,以便listA中的元素優先(這是記錄在案的)。

然後你可以做intersectionResult.Union(listB)。由於listB是交集的超集,因此返回listB,但優先採用intersectionResult的元素。

我認爲這種方法較差,因爲很難斷定它是正確的。聯接方式很簡單。

加入方法還可以讓你扔掉你的自定義比較器,這是一個討厭。

+0

這是正確的嗎? listB.Choices.Join(listA.Choices,p => p.Id,m => m.Id,(a,m)=> new {m.Id,m.Name}); – user1932923

+0

你測試過了嗎?這將放棄對列表不通用的所有項目。 '從B中的B中加入A到...等於...到j讓a = j.SOD()選擇b?了'。看起來像一個神奇的咒語,但它結合了很好理解的模式,如左連接LINQ模式。 – usr

相關問題