mardi 12 janvier 2021

Querying a Array with list of anonymous Object

In my application I have an Array of Objects, The type of all objects will be always same but unknown but I need to update one property of object of array based on some condition

I tried to implement the same like below using reflection

  Public Shared Sub FilterobjectArray(ByVal obj As Object())
     
            Dim r = obj.Where(Function(x) CStr(x.[GetType]().GetProperty("Id")?.GetValue(x)) = "2")

            For Each item In r
                Dim propertyInfo As PropertyInfo = item.[GetType]().GetProperty("CompanyName")
                propertyInfo.SetValue(item, Convert.ChangeType("MyCompany", propertyInfo.PropertyType), Nothing)
            Next           
    End Sub

Problem I think the Lambda expression for filtering the array is wrong as it throws "Object reference not set " in x

My sample implementation

Company Entity

Public Class Company
    Public Property Id As Integer
    Public Property CompanyName As String
End Class

Implementation

    Dim comp(2) As Object
    Dim comp1 = New Company With {.Id = 1, .CompanyName = "Comp1"}
    Dim comp2 = New Company With {.Id = 2, .CompanyName = "Comp2"}
    comp(0) = comp1
    comp(1) = comp2
    FilterobjectArray(comp)

Can Someone Suggest What is wrong ,C# answers or syntax is also welcome

NB: error appears after first iteration in for loop

enter image description here





Aucun commentaire:

Enregistrer un commentaire