C# List as Dictionary key

孤街浪徒 提交于 2019-11-29 03:13:57

The List<custom_obj> instance acting as a key is referentially unequal to the instance referred to by searchObject.

If you want the dictionary to use the values in the list instead of referential equality to find matching keys, you must supply an IEqualityComparer in the constructor of the dictionary (since you can't override Equals and GetHashCode in List<T>).

You have two separate Lists that contain the same elements. The correct way to find out if two lists are equal is with the SequenceEqual method.

You cannot by default do what you are trying to do. You can however, write a custom IEqualityComparer and pass it into the Dictionary constructor.

Here is a sample generic IEqualityComparer:

class ListComparer<T> : IEqualityComparer<List<T>>
{
    public bool Equals(List<T> x, List<T> y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(List<T> obj)
    {
        int hashcode = 0;
        foreach (T t in obj)
        {
            hashcode ^= t.GetHashCode();
        }
        return hashcode;
    }
}

You may want to improve on the GetHashCode implementation, as this was a quick-and-dirty solution.

This will only work if the actual list instance used in the lookup is the same as the instance that was added as a key. It will not compare the list contents. This is the same behavior you will get if you try to compare two List objects directly.

Are you certain that the instance you are using in your lookup method is the same instance that is among your dictionary's keys? That is the only thing I can think of.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!