C# Except comparer 使用小结

C# Except使用小结

使用except 可以将两个list 的内容做比较
可以取得两个list 的差集

// Except
		defaultHoliday.Except(holidays);

如果要对自定义的数据类型进行比较时,可以通过添加Comparer 类的方式来实现

		holidays.AddRange(defaultHolidayEntitys.Except(holidays, new HolidayComparer()));
        // Custom comparer for the Product class
        class HolidayComparer : IEqualityComparer
        {
            // Products are equal if their names and product numbers are equal.
            public bool Equals(HolidayEntity x, HolidayEntity y)
            {

                //Check whether the compared objects reference the same data.
                if (Object.ReferenceEquals(x, y)) return true;

                //Check whether any of the compared objects is null.
                if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                    return false;

                //Check whether the products' properties are equal.
                return x.Name == y.Name;
            }

            // If Equals() returns true for a pair of objects
            // then GetHashCode() must return the same value for these objects.

            public int GetHashCode(HolidayEntity product)
            {
                //Check whether the object is null
                if (Object.ReferenceEquals(product, null)) return 0;

                //Get hash code for the Code field.
                int hashProductCode = product.Name.GetHashCode();

                //Calculate the hash code for the product.
                return hashProductCode;
            }
        }

If comparer is null, the default equality comparer, Default, is used to compare values.

你可能感兴趣的:(.net,C#,c#,.net,windows)