I'm trying to determine the differences between two collections.
private ObservableCollection<SomeObject> _objectList = null;
private ObservableCollection<SomeObject> _cachedObjectList = null;
SomeObject implements IEquatable<SomeObject>
I'm using the following to determine if my two collections have any differences:
this._objectList.ToList().OrderBy(x => x.Id).SequenceEqual(this._cachedObjectList.ToList().OrderBy(x => x.Id));
How can i return a new list that contains any newly added, deleted, or otherwise modified object from the two collections.
Any help would be greatly appreciated!
IEquatable Implementation for SomeObject:
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;
}
}
}
EDIT: I only want the changes, if the _objectList contains a modified object, based on the IEquatable.Equals() then I'd like it returned. Otherwise, return new objects or removed objects in the list.
difference() to get the difference between two lists. Use set() to convert both lists into sets. Use set. difference(s) where set is the first set and s is the second set to get the difference between both sets.
Method 6: Use symmetric_difference to Find the Difference Between Two Lists in Python. The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. The intersection, unlike the shared items of the two sets, is not returned by this technique.
You would find the differences with
var newAndChanged = _objectList.Except(_cachedObjectList);
var removedAndChanged = _cachedObjectList.Except(_objectList);
var changed = newAndChanged.Concat(removedAndChanged);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With