如何在类型的Dictionary中使用ContainsValue

时间:2017-05-16 07:55:43

标签: c# dictionary

我正在创建类的字典,但我无法使用“ContainsValue”方法。请帮忙

我的班级:

 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,我这样做但不起作用:

clsAttendance clsAtt = new clsAttendance();
clsAtt.TagId = 123456AANN;
//---- Check if RFID exists in dictionary or not
bool rfidExists = dicAttendance.ContainsValue(clsAtt);

2 个答案:

答案 0 :(得分:3)

您的班级clsAttendance必须覆盖Equals或实施IEquatable<clsAttendance>。否则,只有它是相同的参考才会被发现。始终覆盖GethashCode

此示例显示了无论如何都推荐的内容:

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);
    }
}

答案 1 :(得分:1)

您可以使用

bool rfidExists = dicAttendance.Values.Any(a => a.TagId.Equals("123456AANN"));