Note that there are some explanatory texts on larger screens.

plurals
  1. POlambda Expression as a property
    text
    copied!<p>I have a working setup which is not strongly typed and relies on reflection.</p> <p>I have a class, say</p> <pre><code>class Person{ public string FirstName {get ; set;} public string LastName {get; set;} public int Age {get; set;} ... // some more public properties } </code></pre> <p>and </p> <pre><code>class CellInfo { public string Title {get; set;} public string FormatString {get; set;} } </code></pre> <p>and I have a dictionary like this</p> <pre><code>Dictionary&lt;string, CellInfo&gt; fields = new Dictionary&lt;string, CellInfo&gt;(); fields.Add("FirstName", new CellInfo {Title = "First Name", FormatString = "Foo"}); fields.Add("LastName", new CellInfo {Title = "Last Name", FormatString = "Bar"}); </code></pre> <p>It's a simple dictionary with property Names and some info about them. I pass the dictionary to another module that processes Person instances and I do</p> <pre><code>Dictionary&lt;string, CellInfo&gt; fields = SomeMethodToGetDictionary(); foreach(Person p in someCollection) { foreach(var field in fields) { object cellValue = type(Person).GetProperty(field.Key).GetValue(p, null); // use cellValue and info on field from field.Value somewhere. ... } } </code></pre> <p>This method of passing the string for field name and using reflection works, but I was wondering if there is a strongly-typed method of doing this.</p> <p>What I had in mind was having a property that stored a linq expression, something like this </p> <pre><code>fields.Add("FirstName", new CellInfo { Title = "First Name", FormatString = "Foo", EvalExpression = p =&gt; p.FirstName }); </code></pre> <p>and during usage, somehow use the <code>EvalExpression</code> on a person object and get the property value. I have no clue where to begin or what the syntax would be like to have a property like this that's evaluateable. I'm new to function delegates and expression trees that I don't even know the right keywords to search for. Hope my description is clear; if not, let me know and I'll details as necessary. Any assistance would much appreciated.</p>
 

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