Mic*_*l G 6 c# collections enumerable
我正在尝试确定两个集合之间的差异.
private ObservableCollection<SomeObject> _objectList = null;
private ObservableCollection<SomeObject> _cachedObjectList = null;
Run Code Online (Sandbox Code Playgroud)
SomeObject实现 IEquatable<SomeObject>
我正在使用以下内容来确定我的两个集合是否存在任何差异:
this._objectList.ToList().OrderBy(x => x.Id).SequenceEqual(this._cachedObjectList.ToList().OrderBy(x => x.Id));
Run Code Online (Sandbox Code Playgroud)
如何从两个集合中返回包含任何新添加,已删除或已修改对象的新列表.
任何帮助将不胜感激!
SomeObject的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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑: 我只想要更改,如果_objectList包含一个修改过的对象,基于IEquatable.Equals()然后我想它返回.否则,返回列表中的新对象或已删除的对象.
你会发现差异
var newAndChanged = _objectList.Except(_cachedObjectList);
var removedAndChanged = _cachedObjectList.Except(_objectList);
var changed = newAndChanged.Concat(removedAndChanged);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
948 次 |
| 最近记录: |