Elegiac
Elegiac

Reputation: 361

Distinct Certain Key Object

i have this certain Key in my Dictionary:

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

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

problem was everytime I generate new Guid, this condition wouldnt work:

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

because Guid key was new ...

Now my question was, how can i make condition that verify if Kkey.Name was already added, then dont add?

Upvotes: 0

Views: 46

Answers (2)

Elegiac
Elegiac

Reputation: 361

can also be

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

Upvotes: 0

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

You either need to create a custom comparer or have your class override Equals and GetHashCode

Option 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());

Option 2: Override

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

Upvotes: 1

Related Questions