【问题标题】:Dynamically creating 1 or more lists in C#在 C# 中动态创建 1 个或多个列表
【发布时间】:2011-06-27 02:07:39
【问题描述】:

我正在尝试构建一个基于数组中字符串数量动态创建列表或数组的方法。名称必须是 Group1、Group2、Group3 等。 我确信 foreach 循环和反射可以实现这一点,但我不确定如何。我以前从未使用过反射。 可能的伪代码:

foreach(string token in array)
{
   CreateList("Group" + number);
}

然后是定义该数字的问题。

【问题讨论】:

  • 你想创建一个视觉数组吗?或者您只是在寻找一种为 N 个字符串创建 N 个列表的方法?一些背景知识可以对此有所帮助。
  • N 个数组中 N 个字符串的列表,是的。

标签: c# arrays reflection loops


【解决方案1】:

我如何理解您的问题,希望此代码对您有所帮助。我假设您要将字符串保存在创建的列表/数组中,因此List<string>

            Dictionary<string, List<string>> dc = new Dictionary<string, List<string>>();
            int count = 0;

            foreach (string group in array)
            {
                dc.Add("Group" + (++count), new List<string>());
            }

            //you can later retrieve the list from dictionary
            if (dc.ContainsKey("Group1"))
            {
                List<string> list = dc["Group1"];
                //and you can then use the list
            }

【讨论】:

    【解决方案2】:

    Dictionary 可能很方便;其中字典的键是“组”+数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2018-07-07
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多