为什么将日期时间值与日期时间值进行比较被视为无效转换
本文关键字:日期 时间 无效 转换 为什么 比较 | 更新日期: 2023-09-27 18:35:12
我有这段代码来比较两个日期时间值:
DateTime currentWeek = Convert.ToDateTime(comboBoxWeekToSchedule.SelectedValue);
List<Student> thisWeeksStudents = (List<Student>)studentsList.Where(i => i.WeekOfLastAssignment.Equals(currentWeek));
学生班与本次讨论最相关的成员是:
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操作(也许是"包含"?),但第一个问题是通过这个无效的强制转换。
这是我在尝试分配给名为"thisWeekStudents"的通用列表后得到的错误的精确文本:
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 http://stackoverflow.com/questions/6346119/datetime-get-next-tuesday
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;
}
如果您收到的错误是...
无法强制转换类型为"WhereListIterator
1[AYttFMScheduler.Student]' to type 'System.Collections.Generic.List
1[AYttFMScheduler.Student]"的对象。
。问题不在于它不能向DateTime
投DateTime
,而在于它不能对List<T>
投WhereListIterator<T>
。我认为您需要做的就是使用ToList()
而不是强制转换,如下所示:
List<Student> thisWeeksStudents = studentsList
.Where(i => i.WeekOfLastAssignment.Equals(currentWeek))
.ToList();
对于 Equals
语句永远不会为真的问题(由于将始终是午夜的日期与具有可变时间的日期进行比较),请尝试获取Date
组件,如下所示:
.Where(i => i.WeekOfLastAssignment.Date == currentWeek)