我有相同的類型和型號的兩個列表低於:一個列表的拷貝複製到另一個使用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());
我想知道這是做的正確方法?
你想確定哪些元素對於兩組是共同的嗎?列表中是否有重複項? – usr
我們想要的唯一通用元素是Id(id始終是唯一的);至於Id匹配,我們正在尋找覆蓋整個對象。可能有ListA有3個對象,而ListB只有1的情況。我們只需要找到1,然後從ListA中更新它。 – user1932923