I have a list of objects defined by the following class:
internal class Aggregate
{
public string fieldName { get; set; }
public double Count { get; set; }
public double Min { get; set; }
public double Max { get; set; }
}
where fieldName
can be Value
, LowLimit
or HighLimit
that I want to transform into a list of objects defined as:
public class KpiValue
{
public double Value { get; set; }
public double? LowLimit { get; set; }
public double? HighLimit { get; set; }
public AggregateType AggregateType { get; set; }
}
public enum AggregateType
{
Count,
Min,
Max
}
I went into it quite naively (Edited with MCVE):
var input = new List<Aggregate> {
new Aggregate() {fieldName = "Value",Count = 5,Min = 2,Max = 3 },
new Aggregate() {fieldName = "HighLimit",Count = 6,Min = 5,Max = 8 },
new Aggregate() {fieldName = "LowLimit",Count = 2,Min = 9,Max = 15 } };
List<KpiValue> values = new List<KpiValue>();
values.Add(new KpiValue()
{
AggregateType = AggregateType.Count,
Value = input.SingleOrDefault(l => l.fieldName == "Value").Count,
HighLimit = input.SingleOrDefault(l => l.fieldName == "HighLimit").Count,
LowLimit = input.SingleOrDefault(l => l.fieldName == "LowLimit").Count
});
values.Add(new KpiValue()
{
AggregateType = AggregateType.Min,
Value = input.SingleOrDefault(l => l.fieldName == "Value").Min,
HighLimit = input.SingleOrDefault(l => l.fieldName == "HighLimit").Min,
LowLimit = input.SingleOrDefault(l => l.fieldName == "LowLimit").Min
});
values.Add(new KpiValue()
{
AggregateType = AggregateType.Count,
Value = input.SingleOrDefault(l => l.fieldName == "Value").Max,
HighLimit = input.SingleOrDefault(l => l.fieldName == "HighLimit").Max,
LowLimit = input.SingleOrDefault(l => l.fieldName == "LowLimit").Max
});
I have been looking around for a way to improve, and it seems like I could, by putting the code in a loop using Reflection as in this question
However, when reading up on how to implement it, I have also learned that reflection is not very efficient, and that it is mostly used with external libraries
In such a case, is Reflection the way to go, or should I keep my duplicated code? (Or is there a better third way?)
Edit:
In this very example, performance is not crucial, as the DB calls are very long, any overhead due to reflection will remain unnoticed. I am merely trying to the the right thing™