对象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!