在用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>();
本文介绍在使用Linq时如何对复杂类型进行去重,通过实现IEqualityComparer接口自定义比较逻辑,适用于包含多个属性的类实例。文章提供了一个具体的例子,展示了从列表中去除重复的QueryCommentModel对象的过程。
2154

被折叠的 条评论
为什么被折叠?



