引用类型List的比较

时间:2021-07-26 09:53:02

一:重新Equals和GetHashCode方法

/// <summary>
    /// 描    述:弹出模型对象列表比较器(根据ID比较)
    /// </summary>
    public class PopupComparer : IEqualityComparer<Model.PopupModel.PopupModel>
    {
        public static PopupComparer Default = new PopupComparer();
        #region IEqualityComparer<PopupModel> 成员
        public bool Equals(Model.PopupModel.PopupModel x, Model.PopupModel.PopupModel y)
        {
            return x.Id.Equals(y.Id);
        }
        public int GetHashCode(Model.PopupModel.PopupModel obj)
        {
            return obj.GetHashCode();
        }
        #endregion
    }

调用:

List<PopupModel> list = new List<PopupModel>();
//model为要比较的对象
if(list.Contains<PopupModel>(model,PopupComparer.Default))
{
}

二:

StudentOldList.Contains(item)

改为
StudentOldList.Any(x => x.Name == item.Name && x.Id == item.Id && x.Ex == item.Ex)