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

3
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 New List(Of turma)
    Dim Disciplinas As New List(Of 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. And from 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 modulo 16 \ Work mod 16 \ Work mod 16 \ F_Contentor.vb 50 9 Work mod 16

What is the correct way to add an item to a list using a structure?

    
asked by anonymous 22.02.2016 / 18:35

2 answers

3

Switch to:

Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    turmas.add(New turma() With { .id_turma = 1 })
End Sub

You need to add an item, and assign a value to it. See the syntax of the Add() method.

Ideally it would be better to use names that are closer to what you usually use with the language. See recommendations for C # that are very similar to VB.Net. You could also consider creating a constructor for the structure.

    
22.02.2016 / 18:46
2

You need to start by creating a Class, I do not recommend using Structure for this kind of problem. You can make a list of structures, but it's simpler and more functional to use a class. Structures are ValueTypes, when you use something like structure (0) = value, you are creating a copy of that value, so unless you have an extreme need or constraint to use a strucure, use a class.

Create the class

Public Class Turma
Public Property IdTurma() As Integer
    Get
        Return m_IdTurma
    End Get
    Set
        m_IdTurma = Value
    End Set
End Property
Private m_IdTurma As Integer
Public Property NomeTurma() As String
    Get
        Return m_NomeTurma
    End Get
    Set
        m_NomeTurma = Value
    End Set
End Property
Private m_NomeTurma As String
End Class

And then instantiate a List of this class.

Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lstTurma As New List(Of Turma)()

lstTurma.Add(New Turma() With { _
    Key .IdTurma = 1, _
    Key .NomeTurma = "Turma do Barulho" _
})
End Sub

To add items to a list, simply use the Add method, where you will add new objects from that class.

    
22.02.2016 / 18:46