繁体   English   中英

如何定义一个字符串数组列表?

[英]How define a string array list?

我想定义一个列表,其元素为3个元素的数组。 下面的代码似乎可以: List<dynamic[]> bb = null; 但是当我尝试时: List<dynamic[3]> bb = null;

它引发错误。 当然,我可以为此创建一个类/结构。 但是有没有办法直接定义它?

这是一种方法:

var list = new List<string[]>();

list.Add(new string[3] { "1", "2", "3" });
list.Add(new string[2] { "1", "2" });

更新:

@Ilya的答案显示了一个带有dynamic的解决方案,但我建议您不要使用dynamic 如果您知道对象的结构,请创建一个类或使用元组,例如

var list = new List<(int id, string name, uint reputation)>();

list.Add((298540, "xiaoyafeng", 11));
list.Add((2707359, "Ilya", 3576));
list.Add((581076, "tymtam", 4421));
list.Add((3043, "Joel Coehoorn", 294378));

我不确定您的问题是什么; 您的标题谈论的是“字符串数组列表”,但是您发布的代码描述了动态数组列表。

我不确定是否会有理由创建一个动态数组列表,但是为了证明您在帖子中讨论的代码可以正常工作,这对我有用:

var stuff = new List<dynamic[]>
{
    new dynamic[] {1, "string"},
    new dynamic[] {DateTime.Now, 45.0}
};

但是,正如其他答案所述,动态是对几类问题的很好的答案。 但是,这不是正确的答案。 问题标题(而不是描述)的正确答案将使用字符串数组列表(如其他答案所指出:

var otherStuff = new List<string[]>
{
    new string[] {"Now", "Is", "the", "time"},
    new string[] {"for all", "good men, etc."}
};

似乎您需要这样的东西:

List<dynamic[]> bb = new List<dynamic[]>();
bb.Add(new dynamic[3]); // here you add a 3-element array
bb.Add(new dynamic[3] { "a", "b", "c" }); // here you add another one 3-element array
// List containing a string array with 3 nulls in it
var aa = new List<string[]> {new string[3]};

// List containing a string array with 3 strings in it
var bb = new List<string[]> {new[] {"a", "b", "c"}};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM