Reputation: 71171
What is the best way to go about this in C#?
string propPath = "ShippingInfo.Address.Street";
I'll have a property path like the one above read from a mapping file. I need to be able to ask the Order object what the value of the code below will be.
this.ShippingInfo.Address.Street
Balancing performance with elegance. All object graph relationships should be one-to-one. Part 2: how hard would it be to add in the capability for it to grab the first one if its a List<> or something like it.
Upvotes: 12
Views: 4906
Reputation: 269658
Perhaps something like this?
string propPath = "ShippingInfo.Address.Street";
object propValue = this;
foreach (string propName in propPath.Split('.'))
{
PropertyInfo propInfo = propValue.GetType().GetProperty(propName);
propValue = propInfo.GetValue(propValue, null);
}
Console.WriteLine("The value of " + propPath + " is: " + propValue);
Or, if you prefer LINQ, you could try this instead. (Although I personally prefer the non-LINQ version.)
string propPath = "ShippingInfo.Address.Street";
object propValue = propPath.Split('.').Aggregate(
(object)this,
(value, name) => value.GetType().GetProperty(name).GetValue(value, null));
Console.WriteLine("The value of " + propPath + " is: " + propValue);
Upvotes: 25
Reputation: 1429
Sounds like a set of nested property invocations:
class X has a property called ShippingInfo; the type represented by ShippingInfo has a property Address; the type represented by Address has a property called Street.
So, assuming that you know the appropriate instance of class X to operate upon:
and so on. You get the picture.
Seems a bit long and tedious, and it is. But that is how you would do it via reflection.
I wonder if it is possible to do the same thing with LINQ to Objects?
The answer to part 2 involves getting the initial value of X from your List<>.
Upvotes: 1