Question

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??

Was it helpful?

Solution

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

OTHER TIPS

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 >

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top