Use LINQ to count the number of combinations existing in two lists
Posted
by Ben McCormack
on Stack Overflow
See other posts from Stack Overflow
or by Ben McCormack
Published on 2010-06-17T21:23:55Z
Indexed on
2010/06/17
21:33 UTC
Read the original article
Hit count: 254
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))
© Stack Overflow or respective owner