I have some data that logs kWh. I want to be able to collect the data and produce a bar chart (I'm using the Microsoft ASP.Net Chart control). I have written code that works, but it looks a little clunky to me and I wondered if somebody could point out a method that may be easier to read and/or more efficient.
The data should normally constantly increase in value though it can be reset. As it is an accumulative value if the values from one period are the same as the previous period then I need to display zero for that time period. Then, when the value does increase, I need to display it as the difference between this period and the last period with a value.
I have the following code to collect the data at hourly intervals only:
myValues = (from values in myEntities.PointValues
where
values.PointID == dataValue &&
SqlFunctions.DatePart("n", values.DataTime) == 0
orderby values.DataTime
select new BarChart
{
Time = values.DataTime,
Value = values.DataValue
}).ToList();
I then use the following code to set the values that are identical in consecutive periods to 0, though, of course, maintaining the first occurrence at its original value:
for (var i = 0; i < myValues.Count - 1; i++)
{
var j = 0;
while (Math.Abs(myValues[i].Value - myValues[i + 1].Value) < double.Epsilon)
{
i++;
j++;
if (i == myValues.Count - 1) break;
}
while (j > 0)
{
myValues[i + 1 - j].Value = 0;
j--;
}
}
Finally, I apply the following code to get the difference in values (difference between value this period and the last period with a positive value).
var subValue = double.MaxValue;
foreach (var t in myValues)
{
if (t.Value > 0 && t.Value < subValue) subValue = t.Value;
if (Math.Abs(t.Value - subValue) > double.Epsilon && Math.Abs(t.Value - 0) > double.Epsilon)
{
var j = t.Value;
t.Value = t.Value - subValue;
subValue = j;
}
}
Which produces my final data.
As I say, this code works fine but if anyone can help with some optimizing/readability, it would be greatly appreciated.
EDIT: For some images see:
https://stackoverflow.com/questions/14425230/can-anyone-assist-with-some-code-optimization