English 中文(简体)
C# List as Dictionary key
原标题:C# List as Dictionary key

我有一个字典,由清单确定:

private Dictionary<List<custom_obj>, string> Lookup;

I m trying to use ContainsKey, but it doesn t seem to be working, and I have no idea why. Here is the debug information from my Visual Studio Immediate Window:

?Lookup.Keys.ElementAt(7)[0]
{custom_obj}
    Direction: Down
    SID: 2540
?Lookup.Keys.ElementAt(7)[1]
{custom_obj}
    Direction: Down
    SID: 2550
searchObject[0]
{custom_obj}
    Direction: Down
    SID: 2540
searchObject[1]
{custom_obj}
    Direction: Down
    SID: 2550
?Lookup.ContainsKey(searchObject)
false

从我的常识来看,最后的锡石应该是真实的。 我希望,我会在这里提供足够信息......任何想法?

感谢!

最佳回答

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

如果您希望词典使用清单中的数值而不是参考性平等来找到相应的钥匙,那么你就必须在以下网站提供IEqualityComparer: 字典的施工/a>(因为你可以在<条码>List<T>上推翻平等与GetHashCode。

问题回答

页: 1 包含相同内容的清单/代码。 如果两个名单都相等,则正确的方法是<代码>SequenceEqual方法。

否则,你无法做你试图做的事情。 但是,你可以撰写一份“标准编码”,将其输入<代码>Dictionary。

此处为通用<编码>。

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;
    }
}

您不妨改进<代码>。 GetHashCode 执行,因为这是一个快速和慷慨的解决办法。

只有在调查中使用的清单实例与作为关键因素增加的情况相同的情况下,才会这样做。 它不会对清单内容进行比较。 如果你试图直接比较两个清单物体,那么你也会这样做。

你们是否相信你在你的看管方法中使用什么就是你所说的钥匙? 这是我所能想象的唯一事情。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签