It all depends on what do you want to do with the arrays when they are already created, how often, etc. The problem is: the "native" .NET arrays are not designed to add and remove elements dynamically after they are created. You can resize the array, but even this is best avoided as it is pretty expensive and hard to maintain. When you need some dynamic behavior, you need to use collections.
Now, let's approach 2D arrays. Let's review all your options from the simplest and least flexible, to the more flexible. Mind you, all the options are quite easy to use and implement.
- 2D array declared as:
string[,] array = new string[numberOfRows, numberOfColumns];
As your example shows different number of elements in different rows, you can designate "unused" element as null
.
This is probably not the most adequate choice, but certainly very simple. - "Jagged array", or array of arrays of strings, declared as
string[][] array = new string[numberOfRows][];
With a jagged array, you can have arrays of different lengths uses as the elements of the outer array. Note that as this is an array if arrays, you can create the outer array once but have to create each inner array separately, in a loop, using new
operator. For example:
array[13] = new string[2] {"1", "2"};
You cannot insert or remove elements, but at any time, you can always replace the element of the outer array with a new instance of an inner array initialized with a different length.
See also http://en.wikipedia.org/wiki/Jagged_array[^]. - The list of the lists of string declared as:
System.Collections.Generic.List<System.Collections.Generic.List<string>> list
= new System.Collections.Generic.List<System.Collections.Generic.List<string>>();
You need to create every internal list (let's say, representing a row of string, as per your example) separately with new
operator; you can add/remove a string element in any inner list and add/remove an inner list as an element of outer list at any time.
Now you know what you can do. Decide what data structure to pick according to the set of operations you require.
—SA