My fledgling programming skills have hit a wall. I could get this working, but the code stinks and I'm convinced there must be a more efficient way I just don't know it yet.
I have a web service that accepts the name of a data property as a parameter. Part of the method for handling the request is to go away and get me a load of data for the specified data property. In my case, it says go and get me the current year's target and actual for the 'electricity usage' property in the database.
In my code this is just like:
var data = rSvc.getDashboardPayload(worklocation, property, year);
The is then delivered as a JSON payload that just says (snipped example):
0: {
month: 1
monthName: "Jan"
currentYearTarget: 100
currentYearActual: 90
}
However, a change has come up that we need to produce a chart that is actually just a total of 4 measures in the database. For example: "Hazardous Waste" is the total of non-metallic waste, plus the total of metallic waste, plus the total of incinerated waste... and so on. You get the picture.
So in my code I can get a payload for each measure like this:
var shwl = rSvc.getDashboardPayload(worklocation, propName, year);
var shwi = rSvc.getDashboardPayload(worklocation, propName, year);
var shmwr = rSvc.getDashboardPayload(worklocation, propName, year);
var shnmwr = rSvc.getDashboardPayload(worklocation, propName, year);
Then I can create a new list that will be my output:
var merged = new List<WLDChartsPayload>(12);
Then I can loop through 12 months and go and total up each measure in turn.
for (short i = 1; i < 13; i++)
{
var m = new WLDChartsPayload();
m.currentYearActual = shwl.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;
m.currentYearActual += shwi.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;
m.currentYearActual += shmwr.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;
m.currentYearActual += shnmwr.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;
m.currentYearTarget = shwl.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;
m.currentYearTarget += shwi.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;
m.currentYearTarget += shmwr.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;
m.currentYearTarget += shnmwr.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;
merged.Add(m);
}
Then I return the merged list.
But this just feels wrong. I have 10 data points in the payload. The code is getting longer and more repetitive.
But, question is, how else can I "totalise and condense" the values from all four of my arrays into a single array?