Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've had to some something similar in the past. I went with the lambda approach because after compiling them I can cache them. I've removed the caching in this code.</p> <p>I included a few unit tests to show the usage of the method. I hope this is helpful.</p> <pre><code>private static object GetValueForPropertyOrField( object objectThatContainsPropertyName, IEnumerable&lt;string&gt; properties ) { foreach ( var property in properties ) { Type typeOfCurrentObject = objectThatContainsPropertyName.GetType(); var parameterExpression = Expression.Parameter( typeOfCurrentObject, "obj" ); Expression memberExpression = Expression.PropertyOrField( parameterExpression, property ); var expression = Expression.Lambda( Expression.GetDelegateType( typeOfCurrentObject, memberExpression.Type ), memberExpression, parameterExpression ).Compile(); objectThatContainsPropertyName = expression.DynamicInvoke( objectThatContainsPropertyName ); } return objectThatContainsPropertyName; } [TestMethod] public void TestOneProperty() { var dateTime = new DateTime(); var result = GetValueForPropertyOrField( dateTime, new[] { "Day" } ); Assert.AreEqual( dateTime.Day, result ); } [TestMethod] public void TestNestedProperties() { var dateTime = new DateTime(); var result = GetValueForPropertyOrField( dateTime, new[] { "Date", "Day" } ); Assert.AreEqual( dateTime.Date.Day, result ); } [TestMethod] public void TestDifferentNestedProperties() { var dateTime = new DateTime(); var result = GetValueForPropertyOrField( dateTime, new[] { "Date", "DayOfWeek" } ); Assert.AreEqual( dateTime.Date.DayOfWeek, result ); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload