【问题标题】:Initializing an Array of HashSet<string>, clarification needed初始化 HashSet<string> 数组,需要说明
【发布时间】:2020-05-31 05:26:09
【问题描述】:

我初始化这样的东西

    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 预初始化为空?

【问题讨论】:

  • 这似乎是正确的。 数组长度为3..且3个值全部为null。数组的容量和长度是一样的。例如,如果使用 List<..>,我希望序列化能够尊重集合的(动态)长度。否则,也许是自定义转换器?这将取决于 JSON 序列化..
  • @user2864740,确实如此。我想知道如果可能的话如何显示 [](初始化为空)而不是 null。
  • 初始化数组长度为0?
  • @LasseV.Karlsen 怎么样?

标签: c# arrays dictionary hashset


【解决方案1】:

我建议将 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"
      ]
    ]
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    相关资源
    最近更新 更多