Reputation: 55946
This IS a delayed execution problem. However, my issue stems from the fact that I cannot ascertain WHY this execution is delayed sometimes, and not other times.
Code:
IList<LineItem> freeFlatItems = new List<LineItem>();
if(QualifyFreeFlatShipping)
freeFlatItems = lineItems.Where(l => l.FlatShippingRate != null).ToList();
decimal? freeFlatShippingTotal = freeFlatItems.Sum(l => l.FlatShippingRate);
var globalShippingPromos = _promoService.GetGlobalShippingPromos();
Problem:
This code is in production, and works as expected. I recently make changese elsewhere and found that this test was not working in our unit testing. When I step through this function the following happens:
lineItems
. Each Item has as value for .FlatShippingRate
true
freeFlatItems = etc...
)freeFlatItems
remains unchanged as execution continues to line 6 (decimal? freeFlatShippingTotal = etc...
).Sum
is executed across an empty list.var globalShippingPromos = etc...
) the value of freeFlatItems
finally updates to what it should be. However... sum was ran on the previous value, and my shipping total is incorrect.The Question(s):
.ToList()
forced the execution of the linq to generate the IList<T>
Upvotes: 1
Views: 123
Reputation: 2107
1.
There is no delayed execution here. The "Where" is forced by ToList(), and the "Sum" is evaluated immediately and stored in the decimal. The error has to be somewhere else
2.
When you evaluate the sum a second time after line 8, lets say with:
decimal? freeFlatShippingTotal2 = freeFlatItems.Sum(l => l.FlatShippingRate);
do you then get the correct value? So, freeFlatShippingTotal2 != freeFlatShippingTotal ?
Upvotes: 2
Reputation: 78262
I don't think this is an issue with delayed execution. But I can suggest a cleaner way for the code to be written.
decimal freeFlatShippingTotal = 0.0m;
if(QualifyFreeFlatShipping)
freeFlatShippingTotal = lineItems.Sum(l => l.FlatShippingRate ?? 0.0m);
Upvotes: 0