從閱讀似乎A.Union(B)
實際上只是增加了A
從B
這些項目是不是已經在A
的documentation。那就是:
當用這種 方法返回的對象被列舉聯盟列舉 第一和第二的順序和 產生具有不 已經得到每個元素。
快速測試證明了這一點。所以oldList.Union(newList)
將保留舊值,而newList.Union(oldList)
會給你新的值。
這裏是我的測試代碼:
class MyThing
{
public string Text { get; private set; }
public int Version { get; private set; }
public MyThing(string t, int v)
{
Text = t;
Version = v;
}
public override int GetHashCode()
{
return Text.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
MyThing other = obj as MyThing;
if (other == null)
return false;
return this.Text.Equals(other.Text);
}
}
static List<MyThing> oldList = new List<MyThing>()
{
new MyThing("Foo", 0),
new MyThing("Bar", 0),
new MyThing("Fooby", 0),
};
static List<MyThing> newList = new List<MyThing>()
{
new MyThing("Barby", 1),
new MyThing("Bar", 1)
};
static void DoIt()
{
var unionOldNew = oldList.Union(newList);
Console.WriteLine("oldList.Union(newList)");
foreach (var t in unionOldNew)
{
Console.WriteLine("{0}, {1}", t.Text, t.Version);
}
Console.WriteLine();
var unionNewOld = newList.Union(oldList);
Console.WriteLine("newList.Union(oldList)");
foreach (var t in unionNewOld)
{
Console.WriteLine("{0}, {1}", t.Text, t.Version);
}
}
@Reed:'newList.Union(oldList)'會做到這一點。看到我的迴應。 –
@Jim:只有在相等比較器按照OP期望的方式處理這個時。但是,鑑於他的陳述,比較者沒有在做OP的比較......(可能是檢查文本和值,而不是文本是否相等)。 –
此查詢具有糟糕的表現。正確的方法是構建一個HashSet或使用GroupJoin。 – usr