C#中IEqualityComparer接口的實現

在用linq寫代碼時,可能會用到去重的功能。若只是string類型的還好,則可通過如下的代碼進行去重:

var testList = (from r in realresultList select r).Distinct<string>().toList<string>();

但若realresultList中包含的是類,則需要對類進行處理。那就用到了IEqualityComparer接口。
具體實現如下:
1、先定義自己的model

	public class QueryCommentModel
    {
        public string NurseStation { get; set; }
        public string DeptID { get; set; }
        public string DeptName { get; set; }
        public string PharmacistID { get; set; }
        public string PharmacistName { get; set; }
        public string OrderCount { get; set; }
        public string RightCommentStatus { get; set; }
        public string ErrorCommentStatus { get; set; }
    }

2、實現接口

	public class QueryCommentModelComparer : IEqualityComparer<QueryCommentModel>
    {
        //實現具體的比較邏輯(與實際業務相關)
        public bool Equals(QueryCommentModel x, QueryCommentModel y)
        {
            bool checkFlag = true;

            if (Object.ReferenceEquals(x, y))
            {
                checkFlag = true;
            }
            else if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            {
                checkFlag = false;
            }
            else
            {
                if (x.NurseStation == y.NurseStation && x.DeptID == y.DeptID && x.PharmacistID == y.PharmacistID)
                {
                    checkFlag = true;
                }
                else
                {
                    checkFlag = false;
                }
            }

            return checkFlag;
        }

        //實現獲取哈希值
        public int GetHashCode(QueryCommentModel model)
        {
            if (Object.ReferenceEquals(model, null)) return 0;

            int hashNurse = model.NurseStation.GetHashCode();
            int hashDeptID = model.DeptID.GetHashCode();
            int hashPharmacist = model.PharmacistID.GetHashCode();
            return hashNurse ^ hashDeptID ^ hashPharmacist;
        }
    }

3、在業務代碼中實現

//通過比較器,實現類的去重
var testList = (from r in realresultList select r).Distinct<QueryCommentModel>(new QueryCommentModelComparer()).ToList<QueryCommentModel>();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章