This question is very similar to a previous question of mine, Use LINQ to count the number of combinations existing in two lists, except with some further twists.
I have a list of CartItems that can receive a discount based on the items specified in the list of DiscountItems. I need to be able to pull out the items in the Cart that can receive a discount and apply the appropriate discount specfied in the DiscountItem. The discount is only applied for each combination that exists. Here's what the two lists might look like to before the discount is applied:
BEFORE DISCOUNT:
CartItems DiscountItems
============================== ===========================
SKU Qty DiscountApplied SKU DiscountAmount
============================== ===========================
Ham 2 $0.00 Ham $0.33
Bacon 1 $0.00 Bacon $2.00
Ham 1 $0.00
Bacon 2 $0.00
Cheese 1 $0.00
Bacon 1 $0.00
The tricky part is that it's not simply a matter of joining the two lists together or counting the number of combinations. The discount is applied for all combinations of DiscountItems that appears in the list of CartItems. There are 3 such combinations in the above example and if you were to apply the discount for the 3 combinations iteratively across the list, the data would look like the following each time the discount is applied:
After 1st Discount is applied:
CartItems DiscountItems
============================== ===========================
SKU Qty DiscountApplied SKU DiscountAmount
============================== ===========================
Ham 2 $0.33 Ham $0.33
Bacon 1 $2.00 Bacon $2.00
Ham 1 $0.00
Bacon 2 $0.00
Cheese 1 $0.00
Bacon 1 $0.00
After 2nd Discount is applied:
CartItems DiscountItems
============================== ===========================
SKU Qty DiscountApplied SKU DiscountAmount
============================== ===========================
Ham 2 $0.66 Ham $0.33
Bacon 1 $2.00 Bacon $2.00
Ham 1 $0.00
Bacon 2 $2.00
Cheese 1 $0.00
Bacon 1 $0.00
After 3rd Discount is applied:
CartItems DiscountItems
============================== ===========================
SKU Qty DiscountApplied SKU DiscountAmount
============================== ===========================
Ham 2 $0.66 Ham $0.33
Bacon 1 $2.00 Bacon $2.00
Ham 1 $0.33
Bacon 2 $4.00
Cheese 1 $0.00
Bacon 1 $0.00
In the end, everything gets a discount except for the cheese and the extra bacon. The cheese doesn't get discounted because it's not a discounted item in the list. The extra bacon doesn't get a discount because it doesn't have a corresponding ham item to qualify for a discount combination. There are a total of 3 hams and 4 bacons, so one of the bacons is not going to get a discount.
I imagine I should be able to solve this problem using LINQ because it involves enumerating over 2 separate lists, but I can't think of what LINQ methods I would use to make this happen. The end result of the LINQ query should be the collection of CartItems with the discount having been applied.