Linq为对象List数据去重

对象List中,对象有多个属性,若想根据某一个属性对List中的数据进行去重操作,可以这样:


对象定义如下:

public class CustomerPhone
    {
        public string FirstName { set; get; }
        public string LastName { set; get; }
        public string Phone { set; get; }
        public string State { set; get; }
        public string TimeZone { set; get; }
        public string ZipCode { set; get; }
    }

生成对象List:

while (csv.ReadNextRecord())
        {
            string phone = csv["Phone No."].ToString();
            if (string.IsNullOrEmpty(phone))
            {
                continue;
            }

            CustomerPhone cp = new CustomerPhone();
            cp.FirstName = csv["Phone No."];
            cp.LastName = csv["Phone No."];
            cp.Phone = csv["Phone No."];
            cp.State = csv["Phone No."];
            cp.TimeZone = csv["Phone No."];
            cp.ZipCode = csv["Phone No."];
            customerPhoneList.Add(cp);
        }

去重前需要定义一个Compare类,实现IEqualityComparer接口

public class CustomerPhoneCompare : IEqualityComparer<CustomerPhone>
{
    public bool Equals(CustomerPhone x, CustomerPhone y)
    {
        return x.Phone == y.Phone; //可以根据某个属性定制去重条件
    }

    public int GetHashCode(CustomerPhone obj) //此方法必须有,作用?
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

实现去重操作:

customerPhoneList.Add(cp);
//。。。添加list后
// phone 去重
var compare = new CustomerPhoneCompare();
var customerPhoneListResult = customerPhoneList.Distinct(compare);//去重的实现!

PortInManage.InsertCustomerPhone(customerPhoneListResult.ToList());//使用结果时需要再转换成list!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值