如何在类型类的Dictionary中使用ContainsValue [英] How to use ContainsValue in Dictionary of type class
本文介绍了如何在类型类的Dictionary中使用ContainsValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建类的词典,但无法使用"ContainsValue"方法.请帮助
I am creating dictionary of class but I am not able to use "ContainsValue" method. Please help
我的课:
class clsAttendance
{
public string TagId { get; set; }
public DateTime LastFoundDate { get; set; }
public DateTime CapturedAt { get; set; }
}
我的字典:
private Dictionary<int, clsAttendance> dicAttendance = new Dictionary<int, clsAttendance>();
我想检查字典中是否存在特定的TagId,我这样做是行不通的:
I want to check if particular TagId exists in dictionary or not, I am doing like this but not working:
clsAttendance clsAtt = new clsAttendance();
clsAtt.TagId = 123456AANN;
//---- Check if RFID exists in dictionary or not
bool rfidExists = dicAttendance.ContainsValue(clsAtt);
推荐答案
您的类clsAttendance
必须重写Equals
或实现IEquatable<clsAttendance>
.否则,只有相同的引用才能找到它.始终也覆盖GethashCode
.
Your class clsAttendance
has to override Equals
or implement IEquatable<clsAttendance>
. Otherwise it's only found if it's the same reference. Always override also GethashCode
.
此示例同时显示了推荐的两种方法:
This example shows both which is recommended anyway:
public class clsAttendance : IEquatable<clsAttendance>
{
public string TagId { get; set; }
public DateTime LastFoundDate { get; set; }
public DateTime CapturedAt { get; set; }
public override bool Equals(object obj)
{
var otherAttendance = obj as clsAttendance;
if (otherAttendance == null)
{
return false;
}
return this.Equals(otherAttendance);
}
public override int GetHashCode()
{
return (this.TagId != null ? this.TagId.GetHashCode() : 0);
}
public bool Equals(clsAttendance other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(this.TagId, other.TagId);
}
}
这篇关于如何在类型类的Dictionary中使用ContainsValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文