C# 实现IEqualityComparer接口去重以及Linq分组去重

有时候我们需要从List<entity>数据源中去重,得需要实现IEqualityComparer接口和重写Equals以及GetHashCode,但是问题来了,如果entity数量很多,得一个一个的去写,有点麻烦,所以这里介绍泛型通用。

先看特性

再看实体类

再看数据源

调用

 达到目的。下面直接上源码

  public class ClassAdapter<T> : IEqualityComparer<T> where T : new()
    {
        private List<PropertyInfo> propertyInfos = null;
        public bool Equals(T? x, T? y)
        {
            if (Object.ReferenceEquals(x, null))
                return false;
            if (Object.ReferenceEquals(y, null))
                return false;
            if (x.GetType() != y.GetType())
                return false;
            if (Object.ReferenceEquals(x, y))
                return true;
            var x_propertyInfos = GetPropertyInfos(x);
            var y_propertyInfos = GetPropertyInfos(y);
            bool status = true;
            for(int i=0;i< x_propertyInfos.Count;i++)
            {
                var x_value = x_propertyInfos[i].GetValue(x);
                var y_value = y_propertyInfos[i].GetValue(y);
                var falge = x_value.Equals(y_value);
                status = status && falge;
                if (!status)
                    break;
            }
            return status;
        }
        public int GetHashCode([DisallowNull] T obj)
        {
            if (Object.ReferenceEquals(obj, null)) 
                return 0;
            int code = 0;
            foreach(var item in GetPropertyInfos(obj))
            {
                code ^= item.GetHashCode();
            }
            return code;
        }
        private List<PropertyInfo> GetPropertyInfos(T obj)
        {
            if (propertyInfos == null)
            {
                var type = obj.GetType();
                var bute = typeof(AdapterAttribute);
                propertyInfos = type.GetProperties().Where(t => t.GetCustomAttributes(bute, false).Length > 0).ToList();
            }
            return propertyInfos;
        }
    }

上面是用泛型+反射+特性达到目的,下面介绍Linq去重

 var data = list.GroupBy(t => new { t.Id, t.Head }).Select(x => x.FirstOrDefault()).ToList();

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值