c# - 初始化一个 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 预初始化为空?
解决方案
我建议将 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"
]
]
}
}
推荐阅读
- python - 如何找到安装python3的路径?
- laravel - 使用 Yajra 数据表获取 Laravel 数据表列的总和
- excel - 创建新工作表时出现 if 语句错误
- haskell - 如何在haskell中调用函数?
- unity3d - 在 iOS 上的 Unity3d 中使用 Agora 播放 AudioFile 时出错
- rust - 字符串切片与切片&字符串
- wpf - 如何在 WPF 中的此图像中的工具提示(单击我)中显示这种阴影方向、阴影深度、颜色?
- python - 如何在使用库时从异步函数启动异步函数而不等待它?(不和谐.py)
- ansible-2.x - 如何将 grep 命令结果存储在 ansible 变量中?
- python - sqlalchemy.exc.OperationalError:(psycopg2.OperationalError)无法连接到服务器:连接超时