代码之家  ›  专栏  ›  技术社区  ›  Chris McCall

根据表达式的结果,我如何将列表分组?

  •  1
  • Chris McCall  · 技术社区  · 14 年前

    我很难表达这个问题,所以请耐心等待,并随时提出后续问题。

    我有一个Period对象和一个函数,其他地方的函数如下所示:

    public static bool PeriodApplies(Period period, DateTime date)
    

    此函数接受一个对象,该对象描述一个周期性周期(例如日程排班或移动电话费率计划周期,即“白天”、“周一从下午5:00到中午12:00”)和一个日期。如果日期在期间内,则返回true。

    现在,我有一个 List<Period> 和A List<Interval> 用一个 Date 财产。如何输出 Dictionary<Period, <Ienumerable<Interval>> (或其他具有类型键的数据结构) Period 和一个值,它是 Interval s)如果PeriodApply在通过时返回true, 间隔 日期 属性和键 时期 ?

    我觉得Linq似乎很适合这类问题,但我不知道如何完成。有什么帮助吗?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Arcturus    14 年前

    像这样:

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

    第一部分给出键,第二部分确定值。

        2
  •  3
  •   Chris McCall    14 年前

    如何使用 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);