当前位置:网站首页>C#中IEqualityComparer接口的实现
C#中IEqualityComparer接口的实现
2022-06-29 09:26:00 【zlbcdn】
在用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>();
边栏推荐
猜你喜欢

EDA与VHDL题库

The Stones Game【取石子博弈 & 思维】

Container of the basic component of the flutter

Simulation problem of two stacks

Picture verification code control

EDA and VHDL question bank

基辅周边的凄美废墟——切尔诺贝利的安全前往指南!

Flutter 基础组件之 Text

Related problems of pointer array, array pointer and parameter passing

Judgment of points inside and outside polygon
随机推荐
Acwing271 [teacher Yang's photographic arrangement] [linear DP]
函数指针、函数指针数组、计算器+转移表等归纳总结
Language characteristics
The collapsing "2.3 * 10 = 22" produced by multiplying float and int
1098 Insertion or Heap Sort (25 分)
信号作品:时变和时不变
走迷宫 bfs 中等+——最后的编程挑战
Listview of the basic component of the shutter
2019.11.13训练总结
To 3 -- the last programming challenge
完全二叉树的权值 递归做法 ——最后的编程挑战
Download control 1 of custom control (downloadview1)
2019.10.27 training summary
HDU 6778 Car (分组枚举-->状压 dp)
HDU 4578 Transformation(线段树+有技巧的懒标记下放)
2019-11-10 training summary
六度空间 bfs
L2-031 深入虎穴 (25 分)
Power Strings【KMP循环节】
Codeforces Round #641 Div2