• 对象集合去重问题?


    List<Data> list = new List<Data>();

    list.Add(new Data { Email = "123", Remark = "345" });
    list.Add(new Data { Email = "abc", Remark = "456" });
    list.Add(new Data { Email = "abc", Remark = "456" });
    list.Add(new Data { Email = "abc", Remark = "789" });

    
    

    //问题1:根据字段去重

    
    

    //方法1

    public class Data:IEquatable<Data>
    {
        public string Email { get; set; }
        public string Remark { get; set; }

    
    

        public bool Equals( Data other)
        {
           return this.Email == other.Email;//根据某个或多个字段去重
        }
        public override int GetHashCode()
        {
           return Email.GetHashCode();
        }
    }

    List<Data> ll = list.Distinct().ToList();

    
    

    //方法2

    public class UserComparer : IEqualityComparer<Data>
    {
         public bool Equals(Data x, Data y)
         {
            if (x == null && y == null)
            {
              return false;
            }
            return x.Email.ToUpper() == y.Email.ToUpper();
         }
         public int GetHashCode(Data obj)
        {
            return obj.ToString().GetHashCode();
        }
    }

     List<Data> l2 = list.Distinct(new UserComparer()).ToList();

    
    

    //方法3
    List<Data> l3 = list.Where((x, i) => list.FindIndex(z => z.Email == x.Email) == i).ToList();

    
    

    //问题2:去重完全相同的对象

    
    

    //方法1
    var list1 = list.Select(a => new { Email = a.Email, ReMark = a.Remark }).Distinct();


    //方法2
    var list2 = (from q in list
    select new
    {
       Email = q.Email,
       Remark = q.Remark
    }).Distinct();

    
    
  • 相关阅读:
    获取Activity中得到焦点的EditText
    SwipeRefreshLayout嵌套ScrollView包裹复杂头布局和RecyclerView
    摄像机识别图片中的手机号
    Glide 加载图片
    反射,元类
    类与实例
    多态
    sys模块理解补充
    python中os模块再回顾
    面向对象之封装
  • 原文地址:https://www.cnblogs.com/xiaohui1990/p/5311681.html
Copyright © 2020-2023  润新知