I have a list of sales records sorted by sales date. I need to fill in the gaps (days without a sales record) in this list with 'inferred sales' records. The method in question calculates an average price for the inferred sales records from its closest valid neighbors that have the same SalesType
. If there's only one neighbor then no need to average it just returns the sales price of the neighbor. I'd like to improve readability of this method.
public class SalesRecord
{
public DateTime Date { get; set; }
public bool IsValid { get; set; }
public int SalesType { get; set; }
public double UnitPrice { get; set; }
}
public class SalesDataContainter
{
private SortedList<DateTime, SalesRecord> salesData;
private double GetInferredPrice(SalesRecord inferredSalesRecord)
{
SalesRecord closestBefore = null;
SalesRecord closestAfter = null;
foreach (var salesRecord in salesData.Values)
{
//neigbor needs to be valid
if (salesRecord.IsValid)
{
continue;
}
//has to have the same sales type
if (salesRecord.SalesType != inferredSalesRecord.SalesType)
{
continue;
}
//listed is sorted get the last found for before neighbor
if (salesRecord.Date < inferredSalesRecord.Date)
{
closestBefore = salesRecord;
}
//listed is sorted get the first found for after neighbor
if (closestAfter == null && salesRecord.Date > inferredSalesRecord.Date)
{
closestAfter = salesRecord;
}
}
// we have neighbors on both sides
if (closestBefore != null && closestAfter != null)
{
return (closestAfter.UnitPrice + closestBefore.UnitPrice) / 2;
}
// there's only before neighbor
if (closestBefore != null)
{
return closestBefore.UnitPrice;
}
// there's only after neighbor
if (closestAfter != null)
{
return closestAfter.UnitPrice;
}
return 0;
}
}