开发者

How can I group a List<K> by a List<T>, depending on the results of an expression<T, K>?

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 Inter开发者_开发技巧vals) 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?


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜