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

Asked

Viewed 135 times

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. A array of a structure. How do I add an item? It’s not leaving me the way I’m doing.

  • You can’t use it List instead of array?

  • Has to be array?

  • No, it does not have to be array. I have now switched to list but give this error: Error 1 'id_turma' is not a Member of 'System.Collections.Generic.List(Of Work_mod_16.turma)'. C: Users Alunop Desktop Work module 16 Work mod 16 Work mod 16 F_container.Vb 69 25 Work mod 16

  • The answer to your original question is given. If now you are doing something else and are making another mistake, ask a new question, given as much detail as possible.

  • I’ll ask another question then. Thank you for the detailed answer.

  • Dude, you make up some typed lists there... you make a class out of the properties you want for the class, and you make a list out of that class, and be happy.

Show 1 more comment

1 answer

2


There is no quick way to do this with array in VB.NET. Arrays were not made to have their size changed. If you need to do this, it is advisable to use a list.

If you really want to do this, you’ll have to change the size of array, what will make a copy of the old to the new. Something like this:

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

I put in the Github for future reference.

No reason not to List (who may have to make the copy as well, but he does it more intelligently than he can).

But if you want to use array even, try to minimize the problem by creating a array sufficient for all required elements. If you only have an idea of the size, create a array which must contain all elements. It will probably be better to have a waste of memory space for unused elements than to have to resize the array. And try to resize a few elements at a time and not one at a time.

If you are going to do this, I strongly advise you to have a method that will manage the addition. That is, that this method checks if it has space, if it does not have the resize. This resize should ideally always double the size of the array whenever necessary. You should start at a reasonable size, 16, for example.

Of course what you’ll be doing is just what the List already does for you without work, without risk of being bugle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.