在列表中添加多个值

是否可以将多个项目添加到列表中或将值列表添加到列表中。

这是我当前的伪代码:

List<string> myList = new List<string>();
myList.add("a","b","c","d","e","f","g");       
myList.add("h","i","j","k","l","m","n");       
myList.add("a1","a2","a3");

我的预期结果是:

[["a","b","c","d","e","f","g"], ["h","i","j","k","l","m","n"], ["a1","a2","a3"]]

任何建议/评论 TIA。


波斯汪
浏览 80回答 2
2回答

开心每一天1111

你要的是一个List<List<string>>. 可能有更好的结构来存储您的数据,但由于您没有提供任何上下文,您可以这样做:var myList = new List<List<string>>();并添加这样的项目:myList.Add(new List<string> { "a", "b", "c", "d", "e", "f", "g" });myList.Add(new List<string> { "h", "i", "j", "k", "l", "m", "n" });myList.Add(new List<string> { "a1", "a2", "a3" });或者在一段代码中使用集合初始化器:var myList = new List<List<string>>{&nbsp; &nbsp; new List<string> { "a", "b", "c", "d", "e", "f", "g" },&nbsp; &nbsp; new List<string> { "h", "i", "j", "k", "l", "m", "n" },&nbsp; &nbsp; new List<string> { "a1", "a2", "a3" }};

子衿沉夜

应该很容易var myList = new List<List<string>>()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new List<string> { "a", "b", "c", "d", "e", "f", "g" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new List<string> { "h", "i", "j", "k", "l", "m", "n" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new List<string> { "a1", "a2", "a3" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;};// ORvar myarray = new[]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new[] { "a", "b", "c", "d", "e", "f", "g" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new[] { "h", "i", "j", "k", "l", "m", "n" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;new[] { "a1", "a2", "a3" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };其他资源对象和集合初始化器(C# 编程指南)C# 允许您在单个语句中实例化对象或集合并执行成员分配。集合初始值设定项集合初始值设定项允许您在初始化实现 IEnumerable 的集合类型时指定一个或多个元素初始值设定项,并将具有适当签名的 Add 作为实例方法或扩展方法。元素初始值设定项可以是简单值、表达式或对象初始值设定项。通过使用集合初始值设定项,您不必指定多个调用;编译器自动添加调用。
打开App,查看更多内容
随时随地看视频慕课网APP