【问题标题】:How to port a multi-keys hash from perl to a c# equivalent?如何将多键哈希从 perl 移植到 c# 等效项?
【发布时间】:2019-10-21 23:54:51
【问题描述】:

在将 perl 模块移植到 c# 代码时,我偶然发现了如何将多键哈希从 perl 移植到 c# 等效项:

$map{$key1}{$key2}=$value;

在要移植的 perl 代码中,我可以使用相同的 key1 定​​义多行,而且我只能使用第一个 key 访问哈希:

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

同样,如果我使用元组作为键,我将能够添加 2 行具有相同 key1(和不同 key2)的行,但我将无法仅使用第一个键访问字典:

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

有什么想法吗?

【问题讨论】:

  • 请记住,$map{$key1}{$key2} = 54;( $map{$key1} //= {} )-&gt;{$key2} = 54; 的缩写,因为它会自动激活。在 C# 中,您需要显式创建子字典。

标签: c# perl dictionary hashmap hashtable


【解决方案1】:

在您的根字典中,只有当新条目不存在时,您才需要添加它。试试这个:

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;

【讨论】:

  • 有趣的方法,让我试试看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 2015-04-13
相关资源
最近更新 更多