如何在非通用ICollection上使用Except运算符?

时间:2014-07-28 13:32:16

标签: c# linq collections

我已经为WMI收集的VS包装器生成了自动生成,如下所示:

// Enumerator implementation for enumerating instances of the class.
    public class DiskDriveCollection : object, ICollection {

        private ManagementObjectCollection privColObj;

        public DiskDriveCollection(ManagementObjectCollection objCollection) {
            privColObj = objCollection;
        }

        public virtual int Count {
            get {
                return privColObj.Count;
            }
        }

        public virtual bool IsSynchronized {
            get {
                return privColObj.IsSynchronized;
            }
        }

        public virtual object SyncRoot {
            get {
                return this;
            }
        }

        public virtual void CopyTo(System.Array array, int index) {
            ...
        }

        public virtual System.Collections.IEnumerator GetEnumerator() {
            return new DiskDriveEnumerator(privColObj.GetEnumerator());
        }

        public class DiskDriveEnumerator : object, System.Collections.IEnumerator {

            private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum;

            public DiskDriveEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) {
                privObjEnum = objEnum;
            }

            public virtual object Current {
                get {
                    return new DiskDrive(((System.Management.ManagementObject)(privObjEnum.Current)));
                }
            }

            public virtual bool MoveNext() {
                return privObjEnum.MoveNext();
            }

            public virtual void Reset() {
                privObjEnum.Reset();
            }
        }
    }

如何使用带有此非通用ICollection的except运算符?

1 个答案:

答案 0 :(得分:1)

ICollection继承自IEnumerable,并且有OfType方法接受IEnumerable并返回IEnumerable<T>,然后您可以轻松使用所有LINQ方法当你得到IEnumerable<T>时,例如:

myCollection.OfType<object>()
.Except(myOtherCollection.OfType<object>(), new CustomEqualityComparer());

由于您有对象,因此需要为它们实现equality comparer并将其传递给Except方法,否则Except将通过引用比较您的对象。