List 去处自定义重复对象方法

时间:2021-11-10 09:06:47

list泛型集合去除重复项,对于单一的某个字段非常简单,但是对于一些自定义要求的还需自定义规则。
例子代码:

/************绑定乘客信息********/
List<RT.Model.TktPassengers> passengerList = (List<RT.Model.TktPassengers>)list[];
//去除重复旅客
List<RT.Model.TktPassengers> newpassengerList = passengerList.Distinct(new TktPassengersComparer()).ToList() ;
rptCustomer.DataSource = newpassengerList;
rptCustomer.DataBind();
  /// <summary>
/// 去除旅客重复
/// </summary>
public class TktPassengersComparer : IEqualityComparer<RT.Model.TktPassengers>
{
public bool Equals(RT.Model.TktPassengers t1, RT.Model.TktPassengers t2)
{
return (t1.PsrName == t2.PsrName && t1.CardNo == t2.CardNo);
}
public int GetHashCode(RT.Model.TktPassengers t)
{
return t.ToString().GetHashCode();
}
}