Ray
Ray

Reputation: 429

How to declare this nested array/list?

I have a custom class Gene

I want to declare an array or list (or something else whatever is better) named _slots with 400 positions...something like _slots[400].

Each _slot must contain a solution. A solution however is an array of my custom class Gene of 100. something like this:

       _Slots
    -------------
0   | Gene[100] |
    --------------
1   | Gene[100] |
    --------------
2   | Gene[100] |
    --------------
3   | Gene[100] |
    --------------
4   | Gene[100] |
    --------------
...
400 | Gene[100] |
    --------------

What's the best way to declare this and have easy access to all members?

Upvotes: 1

Views: 281

Answers (4)

dcastro
dcastro

Reputation: 68710

A much better way is to have a class that represents a Slot, which in turn manages 100 instances of Gene.

Then, have an array of 400 slots (or an IEnumerable, or a List<Slot>, whichever suits your needs).

public class Slot
{
    private Gene[] _genes;

    public Gene this[int index]
    {
        get{ return _genes[index];}
        set{ _genes[index] = value;}
    }

    public Slot(int count = 100)
    {
        _genes = new Gene[count];
    }
}    

IList<Slot> slotsList = Enumerable.Range(0,400)
                              .Select(i => new Slot())
                              .ToList();

//or an enumerable
IEnumerable<Slot> slots = slotsList;

//or an array 
Slot[] slotsArray = slotsList.ToArray();

Upvotes: 2

Jaroslav Kadlec
Jaroslav Kadlec

Reputation: 2543

try use

List<Gene[]> MegaList = new List<Gene[]>();
MegaList.Add(new Gene[100]);
MegaList[0][0] = new Gene();

I strongly recommend wrap this functionality into class, it will allow you to extend it in future easily, f.e.:

public class MultiArray<T> : List<T> { }
...
MultiArray<Gene[]> Storage = new MultiArray<Gene[]>();

Upvotes: 1

Rang
Rang

Reputation: 1372

   List<Gene>[] lst = new List<Gene>[400];

Upvotes: 1

Dennis_E
Dennis_E

Reputation: 8894

Since the length of each dimension is the same, a 2-dimensional array seems logical.

Gene[,]

Alternatively, you can use a List<Gene[]> if the number of arrays is variable instead of a set value of 400

Upvotes: 1

Related Questions