使用变量作为列表名称创建一个两列列表



因为最初的帖子(用变量中的名称创建列表(太旧了,我不想把它当作答案。

但是,我想添加上述解决方案的使用,因为它对我来说并不明显。而且,它可能会帮助我的一些同事。。。此外,我遇到了一些我不知道如何解决的问题。

我需要一种使用变量名创建列表的方法,在这种情况下是";mstrLock";,用于时序图。

不过,我没能让.NET接受两列列表,所以我最终得到了两本词典。

有没有一种方法可以构造它,这样我就可以为两列使用一个字典

dictD.Add("mstrClock", new List<double>());
dictL.Add("mstrClock", new List<string>());

然后,当我开发时序图时,我将其添加到以下列表中:

dictD["mstrClock"].Add(x);  // This value will normally be the time value.
dictL["mstrClock"].Add("L");    // This value will be the "L", "F" or "H" logic level

然后为了获取数据,我这样做了:

for (int n = 0; n < dictD["mstrClock"].Count; n++)
{
listBox1.Items.Add(dictL["mstrClock"][n] + "t" + dictD["mstrClock"][n].ToString());
}

为什么不将您想要显示的内容存储在字典中?

dict.Add("mstrClock", new List<string>());
dict["mstrClock"].Add($"Lt{x}"); 
for (int n = 0; n < dict["mstrClock"].Count; n++)
{
listBox1.Items.Add(dict["mstrClock"][n]);
}

还有一点,你需要字典吗?拥有一本一键词典有什么意义?如果您只需要一个List<string>,那么只需要创建它。

var items = new List<string>());
items.Add($"Lt{x}"); 
foreach (var item in items)
{
listBox1.Items.Add(item);
}

您可以在现代C#中使用元组来创建两列列表,如下所示:

var list = new List<(double time, string logicLevel)>();
list.Add((1, "L"));
list.Add((2, "F"));
foreach (var element in list)
{
listBox1.Items.Add($"{element.time} t {element.logicLevel}");
}

如果必须使用字典,您可以将上面的代码更改为:

var dict = new Dictionary<string, List<(double time, string logicLevel)>>();
dict["mstrClock"] = new List<(double time, string logicLevel)>();
dict["mstrClock"].Add((1, "L"));
dict["mstrClock"].Add((2, "F"));
var list = dict["mstrClock"];
foreach (var element in list)
{
listBox1.Items.Add($"{element.time} t {element.logicLevel}");
}

创建两列列表的一种方法是创建键/值对列表:

var list = new List<KeyValuePair<double, string>();
list.Add(new KeyValuePair<double, string>(1, "L");
foreach (KeyValuePair<double, string> element in list)
{
listBox1.Items.Add($"{element.key} t {element.value}");
}

最新更新