tags:

views:

67

answers:

2

I'm having a difficult time expressing this problem, so bear with me and please feel free to ask followup questions.

I have a Period object, and a function elsewhere that looks like this:

public static bool PeriodApplies(Period period, DateTime date)

This function takes an object that describes a recurring period (think a schedule shift or a mobile phone rate plan period , i.e., "daytime", "Monday from 5:00PM to 12:00AM") and a date. If the date is within the period, it returns true.

Now, I've got a List<Period> and a List<Interval> with a Date property. How can I output A Dictionary<Period, <Ienumerable<Interval>> (or some other data structure with a key of type Period and a value that's a list of Intervals) where the PeriodApplies returns true when passed the Interval's Date property and the key Period?

I feel as though Linq is a good fit for this sort of problem, but I can't figure out how to accomplish this. Any help?

+3  A: 

How about using ToLookup:

var query = (from period in periods
             from interval in intervals
             where PeriodApplies(period, interval)
             select new { period, interval })
            .ToLookup(x => x.period, x => x.interval);
Jon Skeet
+2  A: 

Like so:

IDictionary<Period, IEnumerable<Interval>> dictionary = 
     periods.ToDictionary(p => p, 
                          p => intervals.Where(i => PeriodApplies(p, i.Date)));

First part gives the key, second part determines the values.

Arcturus
I like this answer because it allows me to create a generic function with a predicate for a parameter!
Chris McCall