不同的某些关键对象

时间:2015-02-06 10:41:33

标签: c# dictionary

我的词典中有这个键:

public class KKey
{
    public string Name { get; set; }
    public Guid Guid { get; set; }
}

Dictionary<KKey, string> myDictionary = new Dictionary<KKey, string>();
问题是我每次生成新的Guid时,这个条件都不起作用:

if (false == myDictionary.TryGetValue(key, out keyobj))

因为Guid键是新的......

现在我的问题是,如何确定是否已添加Kkey.Name,然后不添加?

2 个答案:

答案 0 :(得分:1)

您需要创建自定义比较器,或让您的类覆盖EqualsGetHashCode

选项1:比较者

sealed class NameEqualityComparer : IEqualityComparer<KKey>
{
    public bool Equals(KKey x, KKey y)
    {
        return string.Equals(x.Name, y.Name);
    }

    public int GetHashCode(KKey obj)
    {
        return (obj.Name != null ? obj.Name.GetHashCode() : 0);
    }
}

Dictionary<KKey, string> myDictionary = new Dictionary<KKey, string>(new NameEqualityComparer());

选项2:覆盖

public class KKey : IEquatable<KKey>
{
    public string Name { get; set; }
    public Guid Guid { get; set; }

    public bool Equals(KKey other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return string.Equals(Name, other.Name);
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as KKey);
    }

    public override int GetHashCode()
    {
        return (Name != null ? Name.GetHashCode() : 0);
    }
}

Dictionary<KKey, string> myDictionary = new Dictionary<KKey, string>();

答案 1 :(得分:0)

也可以

bool alreadyAdded = keywordList.Any(n => n.Key.Name == name);
if (!alreadyAdded) { }