如何将多键散列从 perl 移植到 c# 等价物?
How to port a multi-keys hash from perl to a c# equivalent?
在将 perl 模块移植到 c# 代码时,我偶然发现了如何将多键散列从 perl 移植到 c# 等效代码:
$map{$key1}{$key2}=$value;
在要移植的perl代码中,我可以用相同的key1定义多行,而且我只能用第一个key访问hash:
# define multiple lines with the same key1 : ex :
$key1 = '1';
$key2 = 'a';
$map{$key1}{$key2}=54;
$key2 = 'b';
$map{$key1}{$key2}=47;
# can access the hash only with the first key : ex :
if (exists($$map{'1'}) {}
但是在 c# 中,如果我使用 c# 字典,我无法添加相同的 key1 行,它表示重复的键。例如,在 c# 中,如果我这样做,就会出现错误:
var map = new Dictionary<string, Dictionary<string, int>>();
map.Add(key1, new Dictionary<string, int>() { { key2, 54 } });
map.Add(key1, new Dictionary<string, int>() { { key2, 47 } });
同样,如果我使用元组作为键,我将能够使用相同的键 1(和不同的键 2)添加 2 行,但我将无法仅使用第一行访问字典键:
var map = new Dictionary<Tuple<string, string>, int>();
map.Add(new Tuple<string, string>(key1, key2), 54);
map.Add(new Tuple<string, string>(key1, key2), 47);
if (map["1"] != null) {} // => this gives an error
有什么想法吗?
在您的根词典中,只有当新条目不存在时,您才需要添加它。试试这个:
key1 = "1";
key2 = "a";
if(!map.TryGetValue(key1, out var subMap))
{
map[key1] = subMap = new Dictionary<string, int>();
}
subMap[key2] = 54;
// somewhere else in code
key1 = "1";
key2 = "b";
if(!map.TryGetValue(key1, out var subMap))
{
map[key1] = subMap = new Dictionary<string, int>();
}
subMap[key2] = 47;
在将 perl 模块移植到 c# 代码时,我偶然发现了如何将多键散列从 perl 移植到 c# 等效代码:
$map{$key1}{$key2}=$value;
在要移植的perl代码中,我可以用相同的key1定义多行,而且我只能用第一个key访问hash:
# define multiple lines with the same key1 : ex :
$key1 = '1';
$key2 = 'a';
$map{$key1}{$key2}=54;
$key2 = 'b';
$map{$key1}{$key2}=47;
# can access the hash only with the first key : ex :
if (exists($$map{'1'}) {}
但是在 c# 中,如果我使用 c# 字典,我无法添加相同的 key1 行,它表示重复的键。例如,在 c# 中,如果我这样做,就会出现错误:
var map = new Dictionary<string, Dictionary<string, int>>();
map.Add(key1, new Dictionary<string, int>() { { key2, 54 } });
map.Add(key1, new Dictionary<string, int>() { { key2, 47 } });
同样,如果我使用元组作为键,我将能够使用相同的键 1(和不同的键 2)添加 2 行,但我将无法仅使用第一行访问字典键:
var map = new Dictionary<Tuple<string, string>, int>();
map.Add(new Tuple<string, string>(key1, key2), 54);
map.Add(new Tuple<string, string>(key1, key2), 47);
if (map["1"] != null) {} // => this gives an error
有什么想法吗?
在您的根词典中,只有当新条目不存在时,您才需要添加它。试试这个:
key1 = "1";
key2 = "a";
if(!map.TryGetValue(key1, out var subMap))
{
map[key1] = subMap = new Dictionary<string, int>();
}
subMap[key2] = 54;
// somewhere else in code
key1 = "1";
key2 = "b";
if(!map.TryGetValue(key1, out var subMap))
{
map[key1] = subMap = new Dictionary<string, int>();
}
subMap[key2] = 47;