I have a dictionary the key for which is a list which is as follows
var dict = new Dictionary<List<MyKey>, Emp>(new MyCustomComparer());
I am having trouble implementing the List comparer. Even though the value exists the containskey always returns false. This is code I have written
Program.cs
var dict = new Dictionary<List<MyKey>, Emp>(new MyCustomComparer());
var key1 = new List<MyKey>
{
{new MyKey{ Name = "string1"}}
};
dict.Add(key1, new Emp());
var key2 = new List<MyKey>
{
{new MyKey{ Name = "string1"}}
};
if (!dict.ContainsKey(key2))
{
dict.Add(key2, new Emp());
}
Key class
public class MyKey
{
public string Name { get; set; }
}
public class Emp
{
}
Comparer class
public class MyCustomComparer : IEqualityComparer<List<MyKey>>
{
public bool Equals(List<MyKey> x, List<MyKey> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<MyKey> obj)
{
return string.Join(",", obj.Select(s => s.Name)).GetHashCode();
}
}
Any help will be much appreciated.
regards
Posting the changed code
var dict = new Dictionary<List<MyKey>, Emp>(new MyCustomComparer());
var key1 = new List<MyKey>
{
{new MyKey{ Name = "string1"}}
};
dict.Add(key1, new Emp());
var key2 = new List<MyKey>
{
{new MyKey{ Name = "string1"}}
};
if (!dict.ContainsKey(key2))
{
dict.Add(key2, new Emp());
}
public class MyKey
{
public string Name { get; set; }
public override int GetHashCode()
{
return Name.GetHashCode();
}
public override bool Equals(object obj)
{
var myKey = obj as MyKey;
if (myKey != null)
{
return Name == myKey.Name;
}
return false;
}
}
public class Emp
{
}
comparer class
public class MyCustomComparer : IEqualityComparer<IEnumerable<MyKey>>
{
public bool Equals(IEnumerable<MyKey> x, IEnumerable<MyKey> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(IEnumerable<MyKey> obj)
{
return string.Join(",", obj.Select(s => s.Name)).GetHashCode();
}
}
Another approach:
public class MyCustomKey : ReadOnlyCollection<MyKey>
{
public override int GetHashCode()
{
return this.Aggregate(0, (c, i) => c + i.Name.GetHashCode()*i.Name.Length);
}
public override bool Equals(object obj)
{
var myKey = obj as MyCustomKey;
if (myKey!= null && myKey.Count == this.Count)
{
return myKey.Zip(this, (i, j) => i.Name == j.Name).All(i=>i);
}
return false;
}
}
var dict = new Dictionary<MyCustomKey, Emp>();
var key1 = new MyCustomKey(new[] {new MyKey {Name = "string1"}});
dict.Add(key1, new Emp());
var key2 = new MyCustomKey(new[] {new MyKey {Name = "string1"}});
if (!dict.ContainsKey(key2))
{
dict.Add(key2, new Emp());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.