我正在尝试确定两个集合之间的差异。
private ObservableCollection<SomeObject> _objectList = null;
private ObservableCollection<SomeObject> _cachedObjectList = null;
SomeObject实现IEquatable<SomeObject>
我正在使用以下内容来确定我的两个馆藏是否有任何差异:
this._objectList.ToList().OrderBy(x => x.Id).SequenceEqual(this._cachedObjectList.ToList().OrderBy(x => x.Id));
如何从两个集合中返回包含任何新添加,删除或以其他方式修改的对象的新列表。
任何帮助将不胜感激!
某些对象的IEquatable实现:
public class SomeObject : IEquatable<SomeObject>
{
public int GetHashCode(SomeObject object)
{
return base.GetHashCode();
}
public bool Equals(SomeObject other)
{
bool result = true;
if (Object.ReferenceEquals(other, null))
{
result = false;
}
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(this, other))
{
result = true;
}
else
{
// if the reference isn't the same, we can check the properties for equality
if (!this.Id.Equals(other.Id))
{
result = false;
}
if (!this.OtherList.OrderBy(x => x.Id).ToList().SequenceEqual(other.OtherList.OrderBy(x => x.Id).ToList()))
{
result = false;
}
}
return result;
}
}
}
修改 我只想要更改,如果_objectList包含一个修改过的对象,基于IEquatable.Equals()然后我想它返回。否则,返回列表中的新对象或已删除的对象。
答案 0 :(得分:7)
你会发现与
的区别var newAndChanged = _objectList.Except(_cachedObjectList);
var removedAndChanged = _cachedObjectList.Except(_objectList);
var changed = newAndChanged.Concat(removedAndChanged);