I have the following method it creates a generic list recursively. I’m getting some interesting results. The property CurrentAllocation is always overwritten with the last value.
Here is the line in question.
courierTypeRegion.CurrentAllocation = remaining;
courierTypeRegionOutput.Add(courierTypeRegion);
Here is the whole method
public static List<CourierTypeRegion> FindClosest2(decimal quantity, decimal remaining, ICollection<CourierTypeRegion> courierTypeRegions, List<CourierTypeRegion> courierTypeRegionOutput)
{
var processed = false;
var courierOrderByDesc = courierTypeRegions.OrderByDescending(x => x.CourierType.PalletsPerTrailer).ToList();
var courierCount = courierOrderByDesc.Count();
var courierCurrent = 0;
foreach (var courierTypeRegion in courierOrderByDesc)
{
if (remaining >= courierTypeRegion.CourierType.PalletsPerTrailer && !processed)
{
courierTypeRegion.CurrentAllocation = courierTypeRegion.CourierType.PalletsPerTrailer;
courierTypeRegionOutput.Add(courierTypeRegion);
processed = true;
}
if (!processed)
{
if (courierOrderByDesc[courierCurrent + 1] != null)
{
if (remaining > courierOrderByDesc[courierCurrent + 1].CourierType.PalletsPerTrailer)
{
courierTypeRegion.CurrentAllocation = remaining;
courierTypeRegionOutput.Add(courierTypeRegion);
processed = true;
}
}
}
courierCurrent++;
}
if (!processed)
{
if (courierTypeRegions.Count > 0)
{
var courierTypeRegionRemaining =
courierTypeRegions.Where(x => x.CourierType.PalletsPerTrailer >= remaining).OrderByDescending(
x => x.CourierType.PalletsPerTrailer).SingleOrDefault();
if (courierTypeRegionRemaining != null) courierTypeRegionOutput.Add(courierTypeRegionRemaining);
processed = true;
}
}
var currentRemaining = quantity - courierTypeRegionOutput.Sum(x => x.CourierType.PalletsPerTrailer);
if (currentRemaining > 0)
{
FindClosest(quantity, currentRemaining, courierTypeRegions, courierTypeRegionOutput);
}
return courierTypeRegionOutput;
}
‘CourierTypeRegion’ is one instance that lives for the entire foreach loop, it is not instantiated and destroyed every loop iteration. You are repeatedly adding the same instance to your list. You end up with a list where all items reference the the last value in the loop.
You need to change your foreach loop as follows: