2010-10-01 128 views
1

我很难表达这个问题,所以请耐心等待,随时提出后续问题。如何根据表达式<T, K>的结果将列表<K>按列表<T>分组?

我有一个时期的对象和功能的其他地方看起来像这样:

public static bool PeriodApplies(Period period, DateTime date) 

这个函数描述的重复周期(想想时间表移动或移动电话计费计划期间,即对象,“白天”,“星期一从下午5点到凌晨12:00”)和日期。如果日期在期限内,则返回true。

现在,我有List<Period>List<Interval>Date属性。我怎样才能输出A Dictionary<Period, <Ienumerable<Interval>>(或其他一些Period类型的密钥和值为Interval s的列表中的其他数据结构)PeriodApplies返回true时通过IntervalDate属性和密钥Period

我觉得Linq很适合这类问题,但我无法弄清楚如何做到这一点。任何帮助?

回答

2

像这样:

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

第一部分描述了密钥,第二部分确定的值。

+1

我喜欢这个答案,因为它允许我创建一个带参数谓词的泛型函数! – 2010-10-01 13:10:45

3

如何使用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); 
相关问题