2015-02-06 85 views
0

我在我的字典此某些关键:鲜明的某些关键对象

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已被添加,然后不添加?

+0

我很好奇,你在字典的字符串部分存储了什么? – Jessica 2015-02-06 10:43:00

+2

您需要使'KKey'工具'IEquatable '。您可能还想将其设置为“结构”,并且在构建之后将属性设置为只读,因为修改字典键是您实际上不想执行的操作。 – Jon 2015-02-06 10:43:15

+0

@Jessica,只是对名称的描述 – Elegiac 2015-02-06 10:46:06

回答

1

要么你需要创建一个自定义比较或有你的类重写EqualsGetHashCode

选项1:的Comparer

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>(); 
+0

@Elegiac你可以使用这种方法使名称不区分大小写,但我认为Guid会最好放在价值而不是密钥中,因为它不构成密钥身份的一部分。 – Jessica 2015-02-06 11:01:52

0

也可以是

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

虽然此代码示例可能会回答该问题,但最好将一些重要的解释包含在答案中。现在看来,这个答案对未来的读者几乎没有任何价值。 – 2015-02-06 12:19:15