I have an object with over 100 properties. I then have a list with a lot of these objects.
I need to calculate the Min, Max, Medium and Median on all the properties in the list.
So instead of writing:
Ag = _valuesForExtraCalculations.Min(c => c.Ag),
Al = _valuesForExtraCalculations.Min(c => c.Al),
Alkal = _valuesForExtraCalculations.Min(c => c.Alkal),
one hundred times, I thought I would be able to use reflection, so I wrote:
var Obj = new Analysis();
Type t = Obj.GetType();
PropertyInfo[] prop = t.GetProperties();
foreach (var propertyInfo in prop)
{
propertyInfo = _valuesForExtraCalculations.Min(?????);
}
But I’m not sure what to write in the foreach loop, so I can set the new min value for that property to the new Analysis object I created.
You would need to know the exact type of the properties. Let’s assume it is
int:If you have different types that you want to calculate the minimum for, you won’t get around checking the types and switching accordingly so the correct overload of
Mingets called.I would still not consider this the best or most performant solution.
PropertyInfo.GetValueandPropertyInfo.SetValueare slower than direct field access (a lot slower according to this article), also it would involve a lot of boxing. You would callPropertyInfo.GetValue(countOfObjects * countOfProperties) times. Depending on the number of items and properties, that might be of concern.