首页 > 解决方案 > 初始化一个 HashSet 数组, 需要澄清

问题描述

我初始化这样的东西

    public Dictionary<int, HashSet<string>[]> historgram = new Dictionary<int, HashSet<string>[]>()
    {
        {0, new HashSet<string>[3]},
        {1, new HashSet<string>[3]},
        {2, new HashSet<string>[3]},
    };

我那时

        if (historgram.TryGetValue(daysAgo, out data))
        {
            if (t.isTestAutomated)
            {
                if (data[0] == null)
                    data[0] = new HashSet<string>();

                data[0].Add(t.id);
            }

以上工作。如果我有数据要放,我会在运行时初始化

完成所有操作后,我编写了一个 Json,并在那些我没有任何东西可放入的实例中以空值结束。它看起来像这样

"historgram": {
  "0": [ null, null, null ],
  "1": [ null, null, null ],
  "2": [ null, null, null ],
  "3": [ null, null, null ],
  "4": [
    [ "XXXX-2244" ],
    null,
    null
  ],

相反,我想以空 [] 结尾。如何立即将 HashSet 预初始化为空?

标签: c#arraysdictionaryhashset

解决方案


我建议将 string[] 更改为 List,以便您可以轻松地管理从 0 到 3 或更大的大小。

public static Dictionary<int, List<HashSet<string>>> historgram = new Dictionary<int, List<HashSet<string>>>()
{
    {0, new List<HashSet<string>>()},
    {1, new List<HashSet<string>>()},
    {2, new List<HashSet<string>>()},
};

您可以像这样在代码中使用上述内容,

if (historgram.TryGetValue(2, out List<HashSet<string>> data)) 
if (data == null)
{
    data = new List<HashSet<string>>();
    data.Add(new HashSet<string>() { "XXXX-2244" });
}
else
{
    data.Add(new HashSet<string>() { "XXXX-2255" });
}

此时,您的原始直方图也已更新。请注意,数据是对字典键值的引用。


dynamic output = new ExpandoObject();
output.histogram = historgram;
Console.WriteLine(JsonConvert.SerializeObject(output, Formatting.Indented));

// Generates the following output...
{
  "histogram": {
    "0": [],
    "1": [],
    "2": [
      [
        "XXXX-2255"
      ]
    ]
  }
}

推荐阅读