0

我有这个 LINQ 查询:

var resourcePlanningInWeek = resourcePlanning.Where(rp => rp.PlanDate >= dateFrom && rp.PlanDate <= dateTo);
var holidays = new HolidayManager().GetByPeriod(dateFrom, dateTo);
var resourcePlanningExcludedHolidays= resourcePlanningInWeek.Where(rpiw => ( holidays.Where(h => h.HolidayDate = rpiw.PlanDate).Count = 0))

执行时,我收到以下错误:

无法将类型“日期时间”隐式转换为“布尔”

有人知道为什么吗?

4

2 回答 2

2
  1. 当你想进行比较时,你需要使用==而不是。=这与最后一行的两个地方有关。
  2. 调用Count缺少括号。
var resourcePlanningExcludedHolidays = resourcePlanningInWeek
    .Where(rpiw => holidays.Where(h => h.HolidayDate == rpiw.PlanDate)
                           .Count() == 0);

但是,有一种更好的写法:

var resourcePlanningExcludedHolidays = resourcePlanningInWeek
    .Where(rpiw => !holidays.Any(h => h.HolidayDate == rpiw.PlanDate));

这更好,因为:

  1. 它更短且更具可读性
  2. holidays一旦条件第一次为真,它就会停止枚举。Count()总是枚举完整的列表。

更好的方法是使用HashSet<DateTime>

var holidays
    = new HashSet<DateTime>(new HolidayManager().GetByPeriod(dateFrom, dateTo)
                                                .Select(x => x.HolidayDate));

var resourcePlanningExcludedHolidays
    = resourcePlanningInWeek.Where(rpiw => !holidays.Contains(rpiw.PlanDate));
于 2012-12-05T12:36:42.733 回答
1

您在以下位置缺少等号:

h.HolidayDate = rpiw.PlanDate

它应该是:

var resourcePlanningExcludedHolidays= 
      resourcePlanningInWeek.Where(rpiw => ( holidays.Where(h => h.HolidayDate == rpiw.PlanDate).Count = 0))
于 2012-12-05T12:30:06.400 回答