xiaoyafeng
xiaoyafeng

Reputation: 41

How define a string array list?

I'd like to define a list whose element is a 3-elements array. Below codes seems ok: List<dynamic[]> bb = null; but when I try: List<dynamic[3]> bb = null;

It throws error. Sure I can create a class/struct for that. But is there a way to define it directly?

Upvotes: 0

Views: 232

Answers (4)

Flydog57
Flydog57

Reputation: 7111

I'm not sure what your issue was; your title talks about a "string array list", but your posted code describes a list of arrays of dynamic.

I'm not sure I'll ever have reason to create a list of arrays of dynamic, but to show that the code that you discussed in your post can work, this works for me:

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

But, as noted in other answers, dynamic is a great answer to several classes of questions. But, it's not the right answer here. The right answer to the title of your question (not the description) will use a list of string arrays (as has been pointed in the other answers:

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

Upvotes: 1

tmaj
tmaj

Reputation: 34957

Here is one way:

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

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

Update:

@Ilya's answer shows a solution with dynamic, but I advise you against using dynamic. If you know the structure of the objects create a class or use a tuple, e.g.

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));

Upvotes: 5

Robyn
Robyn

Reputation: 1374

// 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"}};

Upvotes: 0

Ilya
Ilya

Reputation: 4689

It seems that you need something like this:

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

Upvotes: 0

Related Questions