Faster way to add an item to an array, use a structure

2
Structure turma
    Public id_turma As Integer
    Public nome_turma As String
End Structure

Structure Disciplina
    Public id_disciplinas As Integer
    Public nome_disciplina As Integer
End Structure

Public Class F_Contentor
    Dim turmas() As turma
    Dim disciplina() As Disciplina

Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    turmas().id_turma.add(1)
End Sub

I have this code. An array of a structure. How do I add an 'item'? You're not leaving me the way I'm doing.

    
asked by anonymous 22.02.2016 / 18:08

1 answer

2

There is no quick way to do this with array in VB.Net. Arrays are not meant to have their size changed. If you need to do this, you may want to use a list .

If you really want to do this, you'll have to change < > array , which will make a copy of the old one to the new one. Something like this:

Array.Resize(turmas, turmas.Length + 1);
turmas(turmas.Length - 1) = 1;

You have no reason not to use List (so maybe you have to do the copy as well, but it does it smarter than you can).

But if you want to use array yourself, try minimizing the problem by creating an array of sufficient size for all the necessary elements. If you only have an idea of the size, create an array that should contain all elements. It will probably be better to have a waste of memory space for unused elements than having to be resizing the array . And try resizing some elements at a time instead of one at a time.

If you do this, I strongly advise you to have a method that will administer the addition. That is, this method makes sure you have space, if you do not have resize . This resize should ideally always double the size of the array whenever necessary. It should start with a reasonable size, 16, for example.

Of course, what you're doing is just what List already does for you without work, without risk of being bugado .

    
22.02.2016 / 18:27