我想创建一个循环,使列表的名称需要来自另一个列表。
我试过那样做。
for (int i = 0; i < Names.Count; i++)
{
List<string> Name[i] = new List<string>();
}
在列表构造函数中传递源集合,如下所示
var newList = new List<string>(Names);
如果你想要更多的控制,你仍然可以做你的循环,但是首先声明目标列表:
var newList = new List<string>();
for (int i = 0; i < Names.Count; i++)
{
newList.Add(Names[i]);
}
最后,如果您需要一个列表的列表,其中每个列表命名,您将使用不同的数据结构,例如Dictionary<string, List<string>>
代替:
var listOfLists = new Dictionary<string, List<string>>();
for (int i = 0; i < Names.Count; i++)
{
listOfLists.Add(
Names[i], // <--- the name of the list is the key
new() // <--- the named list (initially empty)
);
}
,可以缩短在现代c#,进一步成为
var listOfLists = Names.ToDictionary(name => name, _ => new List<string>());