vendredi 3 juin 2016

Counting Objects By Their Class

I need to store objects passed to my function in a datatable that is based on their class. I have the ability to create the tables and generate the columns based on the class fields, but currently it will create new tables every time this function is called. I need some kind of counter object that will create a simple list or array of type T so that i can tell my other function that if this counter of T = 0, create new tables, otherwise just add them to the existing table. Only thing i could think of was to individually define each list and instantiate them in a struct, but there is well over 100 classes in this program. (Written in VB.NET)

Here is new item code:

    Function NewItem(Before As IEnumerable(Of Object), After As IEnumerable(Of Object))

    If (ObjectsAreSameClass(Before, After) = False) Then    'If object classes are not the same, send an error message, else continue 
        'Pop error

    Else
        'See if this is the first object, if it is then create tables, else just come back
        IsFirstObject(Before, After)



    End If
    Return Nothing
End Function

Here is what i tried, but does not work because it counts every object created:

   Private Sub IsFirstObject(before As IEnumerable(Of Object), after As IEnumerable(Of Object))

    Dim TempType As Type
    TempType = before.Single.GetType()  'Only need 1 since before and after should be same type

    If (objectCount = 0) Then
        'If this is the first object then we need to generate the datatables and add all of the columns based on class fields.
        ConvertToDataTable(Of Object)(before)
        ConvertToDataTable(Of Object)(after)
        objectCount += 1
    End If

End Sub

And here is my convert from list to data table. All of the objects that are passed to this class are an Ienumerable list. This how my data tables get created based on their class:

Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable

    Dim table As New DataTable()
    Dim fields() As FieldInfo = GetType(T).GetFields()
    For Each field As FieldInfo In fields

        table.Columns.Add(field.Name, field.FieldType)

    Next
    For Each item As T In list

        'Need to see if object is null here so we can set row fields all to null
        Dim row As DataRow = table.NewRow()
        For Each field As FieldInfo In fields
            If (list Is Nothing) Then   'The object was either deleted or created

                row(field.Name) = Nothing

            Else

                row(field.Name) = field.GetValue(item)

            End If
            row(field.Name) = field.GetValue(item)
        Next
        table.Rows.Add(row)
    Next

    Return table

End Function





Aucun commentaire:

Enregistrer un commentaire