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