简体   繁体   English

返回两个枚举之间的差异

[英]Returning the differences between two enumerables

I'm trying to determine the differences between two collections. 我正在尝试确定两个集合之间的差异。

private ObservableCollection<SomeObject> _objectList = null;
private ObservableCollection<SomeObject> _cachedObjectList = null;

SomeObject implements IEquatable<SomeObject> SomeObject实现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));
  • The _cachedObjectList collection will not change. _cachedObjectList集合不会更改。
  • You are able to Add, Remove, Or Modify an object in the _objectList collection. 您可以在_objectList集合中添加,删除或修改对象。

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: 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;
        }
    }
}

EDIT: I only want the changes, if the _objectList contains a modified object, based on the IEquatable.Equals() then I'd like it returned. 编辑:我只想要更改,如果_objectList包含一个修改过的对象,基于IEquatable.Equals()然后我想它返回。 Otherwise, return new objects or removed objects in the list. 否则,返回列表中的新对象或已删除的对象。

You would find the differences with 你会发现差异

var newAndChanged = _objectList.Except(_cachedObjectList);
var removedAndChanged = _cachedObjectList.Except(_objectList);
var changed = newAndChanged.Concat(removedAndChanged);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM