0

so basically I have a class that similar to the following but much longer

Public Class inventory
    Public Property id As Integer
    Public Property name As String
End Class

and in other class I have a list of called order of class inventory so when I loop over the list I can do as

For Each i In orders
        Console.WriteLine(i.name)
Next

but I want a variable to be in the spot . so like

Dim rrr As String = Console.ReadLine()
For Each i In orders
     Console.WriteLine(i.rrr)
Next

however I get error as rrr is not a member in inventory! so please any one know how to solve that and be able to access the class from a variable let me know Thanks

5
  • Maybe a class is not the best way to hold your data, consider using a Dictionary<string, SomeTypeHere> Commented Feb 15, 2020 at 18:29
  • What do you wanted to do with that variable? It's not clear what did you mean by you want a variable to spot? Commented Feb 15, 2020 at 18:45
  • Sorry I ment the variable name in that would change dynamiclly during the run time. Commented Feb 15, 2020 at 19:04
  • Do you mean dim theOrderISeek = orders.FirstOrDefault(function(o) o.Name.Equals(rrr))? (or Contains(rrr) or StartsWith(rrr) or...) Commented Feb 15, 2020 at 19:32
  • rrr is a variable name that it's value point to class property. so in the example above the value of rrr is going to be either name or id Commented Feb 15, 2020 at 19:49

1 Answer 1

1

An answer is provided at Get property value from string using reflection in C# but it is C#. Following is vb.net translation.

Public Class inventory
    Public Property id As Integer
    Public Property name As String
    'I added a custom constructor to make filling a list easier for me
    Public Sub New(i As Integer, n As String)
        id = i
        name = n
    End Sub
    'add back default constructor
    Public Sub New()

    End Sub
End Class

Private orders As New List(Of inventory) From {New inventory(1, "Apples"), New inventory(2, "Oranges"), New inventory(3, "Pears")}

Private Sub OPCode()
    Dim rrr As String = "name" 'Console.ReadLine() as if user typed in name
    For Each i In orders
        Console.WriteLine(GetPropertyValue(i, rrr))
    Next
End Sub

Private Function GetPropertyValue(src As Object, PropName As String) As Object
    Return src.GetType().GetProperty(PropName).GetValue(src, Nothing)
End Function

Output:

Apples

Oranges

Pears

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.