IEqualityComparer自定义比较器

仅当两个对象具有相同的GetHashCode()时才使用Equals()。
如果没有具有相同GetHashCode()的对象,则没有机会使用Equals()。

demo = demo.Distinct(EntityDto.ComparerByKey).ToList();

    public class EntityDto
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }

        public static IEqualityComparer<EntityDto> ComparerByKey { get; } = new EntityDtoEqualityComparer();
    }
    sealed class EntityDtoEqualityComparer : IEqualityComparer<EntityDto>
    {
        public int GetHashCode(EntityDto obj)
        {
            if (obj == null || obj.Property == null || obj.Property2 == null)
            {
                return 0;
            }
            return obj.Property.GetHashCode() ^ obj.Property2.GetHashCode();
        }

        public bool Equals(EntityDto x, EntityDto y)
        {
            if (ReferenceEquals(x, y))
            {
                return true;
            }
            if (ReferenceEquals(x, null))
            {
                return false;
            }
            if (ReferenceEquals(y, null))
            {
                return false;
            }
            if (x.GetType() != y.GetType())
            {
                return false;
            }
            return string.Equals(x.Property, y.Property) && string.Equals(x.Property2, y.Property2);
        }
    }

猜你喜欢

转载自www.cnblogs.com/wesson2019-blog/p/12126310.html
今日推荐