0

Say i have Object1 which has a list of Object2 which has Object3, which has Property1 which i want the value of. Is it possible to have a string in my database like "Object1.Object2[0].Object3.Property1" and then somehow use that within code to navigate that object and get the value for a property i want? I am getting my object i want to navigate to from another api and i basically want to look in my database and see property1 must be > 10 and then dynamically be able navigate that object so i can see if the value in my object passes my criteria in my database. I want to be able to just use database values for this so we can add fields to our database without updating our code. Is this possible?

user1152145
  • 275
  • 1
  • 3
  • 11
  • 1
    Yes, it's possible, but you'll have to write the code yourself to accomplish it. You'll have to parse the string into a sequence of accesses and then execute those accesses against the object. How you do this depends on the types of the objects. – cdhowie Nov 14 '19 at 17:20
  • @cdhowie is correct. For the the individual property accesses, the guide here on using reflection should be useful. https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – Ross Gurbutt Nov 14 '19 at 17:22

2 Answers2

0

Yes, it is definitely possible. You'll want Object1 to be a dynamic object, so that you can access its properties using variables e.g. Object1["Object2"][0]. Then all you need is to work out a consistent format for your database strings, with your example you could split by . and use a loop to access and store each property in the result successively.

See this question for info on dynamic objects from JSON (assuming that's the format you receive it in from your API) or if you'd prefer to use reflection, this question has info about that.

Klaycon
  • 10,599
  • 18
  • 35
0

I found a nuget package to do exactly what i wanted. https://github.com/Domysee/Pather.CSharp

user1152145
  • 275
  • 1
  • 3
  • 11