sooprise
sooprise

Reputation: 23187

Jagged Array Dimensions

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

Upvotes: 1

Views: 738

Answers (4)

Bill W
Bill W

Reputation: 1498

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.

Upvotes: 0

Charlie Salts
Charlie Salts

Reputation: 13498

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.

Upvotes: 1

Justin
Justin

Reputation: 4624

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

Upvotes: 0

dreadwail
dreadwail

Reputation: 15410

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 >

Upvotes: 1

Related Questions