使用字典作为其他字典中的关键 [英] using dictionary as a key in other dictionary

查看:156
本文介绍了使用字典作为其他字典中的关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在另一个字典中使用字典作为 TKey 。类似于python的东西。我试过这个,但是它给了我错误。

I would like to use Dictionary as TKey in another Dictionary. Something similar to python. I tried this but it gives me errors.

Dictionary<Dictionary<string, string>, int> dict = new Dictionary<Dictionary<string,    string>, int>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["abc"] = "def";
dict[dict["abc"] = 20;


推荐答案

给你什么错误?是否抱怨您在第4行的缺失支架?

What error is it giving you? Is it complaining about your missing bracket on line 4?

第4行看起来应该是:

dict[dict["abc"]] = 20;

但是,您可能意味着这一点,因为abc不是dict的关键:

However, you probably mean this, since "abc" is not a key of dict:

dict[dict2["abc"]] = 20;

dict2 [abc] 一个字符串,当dict的关键字应该是一个字典< string,string>

But dict2["abc"] is a string, when the key of dict is supposed to be a Dictionary<string, string>.

但是,在这个路径走得很远之前,我们再来重新检查一下原来的目标。您不应该首先将可变类型用作字典键。

But let's re-examine your original goal at this point before going to far down this path. You shouldn't be using mutable types as dictionary keys in the first place.

这可能是您要查找的代码:

This may be the code you're looking for:

Dictionary<string, int> dict  = new Dictionary<string, int>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["abc"] = "def";
dict[dict2["abc"]] = 20;

但是很难确定。

这篇关于使用字典作为其他字典中的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆