2015-02-06 80 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