【问题标题】:Initialize Array of Dictionary Randomly随机初始化字典数组
【发布时间】:2018-10-12 09:11:42
【问题描述】:

我正在处理字典数组,this SO Post 对实现我目前想要的非常有帮助。

但是,现在我想根据代码的输出为数组索引初始化Dictionary

我有一个Dictionary<int,string>,我在其中存储了一个Id 作为密钥。我有 10 个字典的数组,如下所示:

Dictionary<int, string>[] matrix = new Dictionary<int, string>[10];

因此,基于(Id%10) 的值,我想将该记录存储在相应的数组中。例如,如果id= 12,我想将其存储在matrix[2]。如果id = 15,我想将其存储在matrix[5]

现在,问题是,如何每次检查字典是否为特定索引初始化。如果是,则将记录添加到字典中,否则初始化实例,然后将记录添加到字典中。

类似以下内容:

if {} // if dict with id%10 is initialized then
{
    matrix[id%10].Add();
}
else
{
    matrix[id%10] = new Dictionary<int,string>();
    matrix[id%10].Add();
}

编辑:我知道我可以先使用循环初始化所有内容,但我只想在必要时进行初始化。

【问题讨论】:

  • @Adrian 这将检查密钥是否在字典中。我的问题不同。
  • 对。只需检查matrix[index] == null
  • 如果一个数组中只有10个字典,那么在创建数组之后将它们全部实例化不是更容易吗?
  • @Adrian Thnx。不知道我怎么没想到。
  • @dymanoid 我有很多字典数组,数组大小超过 10。因此我想避免这种情况。

标签: c# .net arrays dictionary


【解决方案1】:
    Dictionary<int, string>[] matrix = new Dictionary<int, string>[10];
    int id = 0; // Number here
    int index = id % 10;

    if (matrix[index] == null)
    {
        matrix[index] = new Dictionary<int, string>();
    }

    int key = 0; // key you want to insert

    if (matrix[index].ContainsKey(key))
    {
        // Dictionary already has this key. handle this the way you want
    }
    else
    {
        matrix[index].Add(0, ""); // Key and value here
    }

【讨论】:

  • 好的。这太容易了,对我来说真的很尴尬。谢谢。
  • @HarshilDoshi 没问题。请注意,此处还需要进行密钥检查。否则,您最终可能会遇到异常
  • @mjwills 为什么?我们只是想看看一个键是否存在。
  • TryGetValue 的优势在于,如果// Dictionary already has this key. handle this the way you want 需要访问存储在Dictionary 中的对象,则无需再次进行哈希查找即可。
  • 在那种情况下。当然。仅当我们需要与键关联的现有值时。
猜你喜欢
  • 2016-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
相关资源
最近更新 更多