Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As far as I've understood your question, you can achieve this using expressions:</p> <pre><code>/// &lt;summary&gt; /// A class with many-many properties /// &lt;/summary&gt; class MyClass { public Decimal A { get; set; } public Decimal B { get; set; } public Decimal C { get; set; } } class PropertyHelper&lt;T, TProperty&gt; { private readonly Func&lt;T, TProperty&gt; selector; private readonly Action&lt;T, TProperty&gt; setter; public PropertyHelper(Func&lt;T, TProperty&gt; selector, Action&lt;T, TProperty&gt; setter) { this.selector = selector; this.setter = setter; } public Func&lt;T, TProperty&gt; Selector { get { return selector; } } public Action&lt;T, TProperty&gt; Setter { get { return setter; } } } class AggregateHelper&lt;T, TProperty&gt; { private readonly Dictionary&lt;PropertyInfo, PropertyHelper&lt;T, TProperty&gt;&gt; helpers; public AggregateHelper() { this.helpers = typeof(T) .GetProperties() .Where(p =&gt; p.PropertyType == typeof(TProperty)) .ToDictionary(p =&gt; p, p =&gt; new PropertyHelper&lt;T, TProperty&gt;(MakeSelector(p), MakeSetter(p))); } private Func&lt;T, TProperty&gt; MakeSelector(PropertyInfo property) { var parameterExpr = Expression.Parameter(typeof(T)); var lambda = (Expression&lt;Func&lt;T, TProperty&gt;&gt;)Expression.Lambda( Expression.Property(parameterExpr, property), parameterExpr); return lambda.Compile(); } private Action&lt;T, TProperty&gt; MakeSetter(PropertyInfo property) { var instanceExpr = Expression.Parameter(typeof(T)); var parameterValueExpr = Expression.Parameter(typeof(TProperty)); var lambda = (Expression&lt;Action&lt;T, TProperty&gt;&gt;)Expression.Lambda( Expression.Call(instanceExpr, property.GetSetMethod(), parameterValueExpr), instanceExpr, parameterValueExpr); return lambda.Compile(); } public IEnumerable&lt;PropertyInfo&gt; Properties { get { return helpers.Keys; } } public PropertyHelper&lt;T, TProperty&gt; this[PropertyInfo property] { get { return helpers[property]; } } } </code></pre> <p>Usage: </p> <pre><code> public static void Do() { var target = new MyClass(); var list = new List&lt;MyClass&gt; { new MyClass { A = 1M, B = 2M, C = 3M }, new MyClass { A = 10M, B = 20M, C = 30M }, new MyClass { A = 100M, B = 200M, C = 300M } }; // calculate 'min' for all decimal properties var helper = new AggregateHelper&lt;MyClass, Decimal&gt;(); foreach (var property in helper.Properties) { var propertyHelper = helper[property]; propertyHelper.Setter(target, list.Min(propertyHelper.Selector)); } } </code></pre> <p>Compiled lambdas work faster then reflection, and there will be no boxing/unboxing.</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