Use LINQ to count the number of combinations existing in two lists
- by Ben McCormack
I'm trying to create a LINQ query (or queries) that count the total number of occurences of a combinations of items in one list that exist in a different list. For example, take the following lists:
CartItems DiscountItems
========= =============
AAA AAA
AAA BBB
AAA
BBB
BBB
CCC
CCC
DDD
The result of the query operation should be 2 since I can find two combinations of AAA and BBB (from DiscountItems) within the contents of CartItems.
My thinking in approaching the query is to join the lists together to shorten CartItems to only include items from DiscountItems. The solution would be to find the CartItem in the resulting query that occurs the least amount of times, thus indicating how many combinations of items exist in CartItems.
How can this be done?
Here's the query I already have, but it's not working. query results in an enumeration with 100 items, far more than I expected.
Dim query = From cartItem In Cart.CartItems
Group Join discountItem
In DiscountGroup.DiscountItems
On cartItem.SKU Equals discountItem.SKU
Into Group
Select SKU = cartItem.SKU, CartItems = Group
Return query.Min(Function(x) x.CartItems.Sum(Function(y) y.Quantity))