I have following list of objects
List < Percentages > MyList which contains values
date high low avg
2014-08-21 16:15:00 20 10 22.5
2014-08-21 16:12:00 21 11 02
2014-08-21 16:09:00 25 12 23
2014-08-21 16:08:00 23 16 22
2014-08-21 16:07:00 19 09 21
2014-08-21 16:04:00 35 20 21.5
2014-08-21 16:03:00 45 25 19.5
2014-08-21 16:00:00 64 20 33.5
2014-08-21 15:56:00 32 25 27.5
public class Percentages
{
public DateTime Date { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Average { get; set; }
}
As can be seen the list has some missing minutes . My goal is to add missing minutes to list with the values of previous date. Something like :
date high low avg
2014-08-21 16:15:00 20 10 22.5
2014-08-21 16:14:00 21 11 02
2014-08-21 16:13:00 21 11 02
2014-08-21 16:12:00 21 11 02
2014-08-21 16:11:00 25 12 23
2014-08-21 16:10:00 25 12 23
2014-08-21 16:09:00 25 12 23
2014-08-21 16:08:00 23 16 22
2014-08-21 16:07:00 19 09 21
2014-08-21 16:06:00 35 20 21.5
2014-08-21 16:05:00 35 20 21.5
2014-08-21 16:04:00 35 20 21.5
2014-08-21 16:03:00 45 25 19.5
2014-08-21 16:02:00 64 20 33.5
2014-08-21 16:01:00 64 20 33.5
2014-08-21 16:00:00 64 20 33.5
2014-08-21 15:59:00 32 25 27.5
2014-08-21 15:58:00 32 25 27.5
2014-08-21 15:57:00 32 25 27.5
2014-08-21 15:56:00 32 25 27.5
I did something like this (see below) but it seems a bit tricky probably with LINQ would be easier :
Mylist < Percentages > = ....
List< Percentages > tempList = new List <Percentages >
for (int j = tempList.Count - 1; j> 0; j--)
{
if ( (tempList[j-1].Date - tempList[j].Date).TotalMinutes >1)
{
candles.Add(Mylist[j]);
}
}
This should work, i've used LINQ since you've asked for. In general your requirement depends heavily on consecutive elements which is often an indication that you should use a plain loop instead of LINQ.
// ensure that it's sorted by date
percentages.Sort((p1, p2) => p1.Date.CompareTo(p2.Date));
List<Percentages> newPercentages = new List<Percentages>();
foreach (Percentages percentage in percentages)
{
Percentages lastPercentage = newPercentages.LastOrDefault();
if (lastPercentage != null)
{
TimeSpan diff = percentage.Date - lastPercentage.Date;
int missingMinutes = (int)diff.TotalMinutes - 1;
if(missingMinutes > 0)
{
var missing = Enumerable.Range(1, missingMinutes)
.Select(n => new Percentages
{
Date = lastPercentage.Date.AddMinutes(n),
Average = lastPercentage.Average,
High = lastPercentage.High,
Low = lastPercentage.Low
});
newPercentages.AddRange(missing);
}
}
newPercentages.Add(percentage);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With