为什么将 DateTime 值与 DateTime 值进行比较被视为无效转换?

Why is comparing a DateTime value to a DateTime value considered an invalid cast?

我有这段代码可以比较两个 DateTime 值:

DateTime currentWeek = Convert.ToDateTime(comboBoxWeekToSchedule.SelectedValue);
List<Student> thisWeeksStudents = (List<Student>)studentsList.Where(i => i.WeekOfLastAssignment.Equals(currentWeek));

学生 class' 与此讨论最相关的成员是:

public DateTime WeekOfLastAssignment { get; set; }

这一行之后:

DateTime currentWeek = Convert.ToDateTime(comboBoxWeekToSchedule.SelectedValue);

...执行,"currentWeek"的值为“2/22/2016 12:00:00 AM

我正在尝试过滤 "WeekOfLastAssignment" 元素等于 "currentWeek" 值的元素的通用列表;这些表示(如在调试器中所见)为“{8/14/2015 10:52:55 PM}

IOW,它们似乎具有相同的格式(除了包裹“{”和“}”,我怀疑这是问题所在)。

我可以看出可能没有完全匹配,因为组合框值始终将午夜作为其时间元素。所以也许我将不得不执行 "LIKE %" 类型的 LINQ 操作("Contains" 可能?),但第一个问题是通过这个无效的转换。

这是我在尝试分配给名为 "thisWeeksStudents":

的通用列表后得到的错误的准确文本
System.InvalidCastException was unhandled
  HResult=-2147467262
  Message=Unable to cast object of type 'WhereListIterator`1[AYttFMScheduler.Student]' to type 'System.Collections.Generic.List`1[AYttFMScheduler.Student]'.

我需要做什么来纠正这种情况?

如果它可能是相关的,comboBoxWeekToSchedule 填充如下值:

private void PopulateComboBoxWithSchedulableWeeks()
{
    int WEEKS_TO_OFFER_COUNT = 13;
    List<String> schedulableWeeks = AYttFMConstsAndUtils.GetWeekBeginnings(WEEKS_TO_OFFER_COUNT).ToList();
    BindingSource bs = new BindingSource();
    bs.DataSource = schedulableWeeks;
    comboBoxWeekToSchedule.DataSource = bs;
}

public static List<String> GetWeekBeginnings(int countOfWeeks)
{
    // from 
    DateTime today = DateTime.Today;
    // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
    int daysUntilMonday = ((int)DayOfWeek.Monday - (int)today.DayOfWeek + 7) % 7;
    DateTime nextMonday = today.AddDays(daysUntilMonday);

    List<String> mondays = new List<string>();
    // Need all Mondays, even though 1st Monday is BR only
    if (!IsAssemblyOrConventionWeek(nextMonday))
    {
        mondays.Add(nextMonday.ToLongDateString());
    }

    for (int i = 0; i < countOfWeeks; i++)
    {
        nextMonday = nextMonday.AddDays(7);
        if (!IsAssemblyOrConventionWeek(nextMonday))
        {
            mondays.Add(nextMonday.ToLongDateString());
        }
    }
    return mondays;
}

如果您遇到的错误是...

Unable to cast object of type 'WhereListIterator1[AYttFMScheduler.Student]' to type 'System.Collections.Generic.List1[AYttFMScheduler.Student]'.

...问题不是它不能将 DateTime 转换为 DateTime,而是它不能将 WhereListIterator<T> 转换为 List<T>.我认为您需要做的就是使用 ToList() 而不是强制转换,如下所示:

List<Student> thisWeeksStudents = studentsList
    .Where(i => i.WeekOfLastAssignment.Equals(currentWeek))
    .ToList();

对于 Equals 语句永远不正确的问题(由于比较总是午夜的日期与具有可变时间的日期),请尝试获取 Date 组件,例如这个:

.Where(i => i.WeekOfLastAssignment.Date == currentWeek)