Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Object value by string path [duplicate]

I have this string
Member.User.Name

and this instance:

Root root = new Root();
root.Member.User.Name = "user name";

How do I extract the value from root of the member Member.User.Name

for example:

string res = GetDeepPropertyValue(root, "Member.User.Name");

res will be "user name"

Thanks

like image 300
SexyMF Avatar asked Aug 16 '26 04:08

SexyMF


1 Answers

Try this:

public object GetDeepPropertyValue(object instance, string path){
  var pp = path.Split('.');
  Type t = instance.GetType();
  foreach(var prop in pp){
    PropertyInfo propInfo = t.GetProperty(prop);
    if(propInfo != null){
      instance = propInfo.GetValue(instance, null);
      t = propInfo.PropertyType;
    }else throw new ArgumentException("Properties path is not correct");
  }
  return instance;
}
string res = GetDeepPropertyValue(root, "Member.User.Name").ToString();

NOTE: We don't need recursive solution for this because the number of loops is known beforehand. Using foreach would be more efficient if possible. We use recursion only when the implementation becomes complicated with for - foreach.

like image 74
King King Avatar answered Aug 17 '26 19:08

King King



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!