2

I have a list called DiscountableObject. Each item on the list in turn has a Discounts collection. What I need is a list of Discounts which are common across all DiscoubtableObjects.

Code:

List<Discount> IntersectionOfDiscounts = new List<Discount>();
foreach(var discountableItem in DiscoutableObject)
{
    IntersectionOfDiscounts = IntersectionOfDiscounts.Intersect(discountableItem.Discounts);    
}

This will undoubtedly return an empty list because by IntersectionOfDiscounts was empty in the first instance.

What I want is to take item 1 of the DiscountableObject, compare it with the next item of DiscountableObject and so on.

I know what I am trying to do is wrong because, I am doing the intersection and the addition to the list at the same time...but how else baffles me?

How do I get around this?

Magic
  • 137
  • 1
  • 8

2 Answers2

4

Initialize IntersectionOfDiscounts to the first Discount List (if there is more than one) rather than to an empty list. You can also then skip the first item in the 'foreach' loop.

// add check to ensure at least 1 item.
List<Discount> IntersectionOfDiscounts = DiscoutableObject.First().Discounts; 
foreach(var discountableItem in DiscoutableObject.Skip(1))
{
    IntersectionOfDiscounts = IntersectionOfDiscounts.Intersect(discountableItem.Discounts);    
}
Servy
  • 202,030
  • 26
  • 332
  • 449
  • There must be a more elegant way than this... but yes, it'll work :) – Rawling Apr 04 '12 at 15:31
  • You could make a new `IEnumerable` extension for Intersect that performed an intersect on N Enumerables (i.e. an Enumerable of Enumerables) if you did this often enough. – Servy Apr 04 '12 at 15:32
  • Duh! I now feel like an idiot! Will mark the answer as accepted in 6 minutes unless there is a better one. Thanks! – Magic Apr 04 '12 at 15:37
3

Possibly more elegant way:

var intersection = discountableObject
   .Select(discountableItem => discountableItem.Discounts)
   .Aggregate( (current, next) => current.Intersect(next).ToList());

Missed your 6 minute deadline, but I like it anyway...

Mike Goodwin
  • 8,810
  • 2
  • 35
  • 50