views:

70

answers:

4

I'm using jagged arrays and have a bit of a problem (or at least I think I do). The size of these arrays are determined by how many rows are returned in a database, so it is very variable. The only solution I have is to set the dimensions of the array to be very huge, but this seems ... just not the best way to do things.

int[][] hulkSmash = new int[10][];
hulkSmash[0] = new int[2] {1,2};

How can I work with jagged arrays without setting the dimensions, or is this just a fact of life with C# programming??

A: 

You've got 2 choices:

  • You can read the size of the information returned from the database, and allocate your array space at that time, once you know what you're getting.
  • Otherwise, what you're looking for is a data structure that has variable dimensions. Take a look at List for example: MSDN: List< T >
byte
A: 
List<List<int>> hulkSmash = new List<List<int>>();
hulkSmash.Add(new List<int>() { 1, 2 });

or

List<int[]> hulkSmash = new List<int[]>();
hulkSmash.Add(new int[] { 1, 2 });
Justin
Since I've never worked with a list before, which is the preferred method? A list of lists or a list or arrays?
Soo
If you know how big the inner lists are and they will never need to be modified then an array is lighter and there is really no 'need' for it to be a list. If there is ANY chance that you will need to modify it or wont know the initial size then a list would be preferred.
Justin
A list uses an array internally. It just handles all of the resizing, etc., for you.
Justin
A: 

A collection of ints will give you the flexibility that you want and not waste space the way as allocating an array that is much larger than you will ever need.

Bill W
+1  A: 

The other examples using List<T> and collections are the best way to proceed. I sometimes find the

List<List<int>> hulkSmash = new List<List<int>>();

syntax a tad unwieldy. Luckily, there are some options to manage this.

The first option I sometimes use is to make an alias:

using List<List<int>> = HulkSmashCollection;

This prevents you from having to do nested <<<Types>>> all the time. Everywhere you'd type List<List<int>> you can instead type HulkSmashCollection (or something shorter still) instead.


The second option is to wrap the List of Lists within a class called, say, MyHulkSmashes. Here, you only provide the functions/properties you need, like Count or Find() etc.

Both these concepts are used to reduce the amount of code on screen, and reduce perceived complexity.

Charlie Salts
...or even declare a `public class HulkSmashCollection: List<List<int>> {}`
Peter Lillevold
Best way to go through a list? Loop through using foreach?
Soo
Yes, although there are caveats. The collection may not change during iteration. Thus, adding or removing items from a list (or any IEnumerable collection, for that matter) will throw an exception.
Charlie Salts
Although not recommended, you can alter items in a list by looping backwards through it...
Justin