B. *_*non 0 c# linq datetime generic-list date-comparison
我有这个代码来比较两个DateTime值:
DateTime currentWeek = Convert.ToDateTime(comboBoxWeekToSchedule.SelectedValue);
List<Student> thisWeeksStudents = (List<Student>)studentsList.Where(i => i.WeekOfLastAssignment.Equals(currentWeek));
Run Code Online (Sandbox Code Playgroud)
学生班与本次讨论最相关的成员是:
public DateTime WeekOfLastAssignment { get; set; }
Run Code Online (Sandbox Code Playgroud)
在此之后:
DateTime currentWeek = Convert.ToDateTime(comboBoxWeekToSchedule.SelectedValue);
Run Code Online (Sandbox Code Playgroud)
...执行,"currentWeek"的值是"2/22/2016 12:00:00 AM "
我试图过滤"WeekOfLastAssignment"元素等于"currentWeek"值的元素的通用列表; 这些(如调试器中所示)表示为" {8/14/2015 10:52:55 PM} "
IOW,它们似乎具有相同的格式(除了包装"{"和"}",我怀疑是问题).
我可以看到可能没有确切的匹配,因为组合框值总是有午夜作为他们的时间元素.所以也许我将不得不执行一个"LIKE%"类型的LINQ操作("包含"可能?),但第一个问题是越过这个无效的强制转换.
这是我尝试分配到名为"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]'.
Run Code Online (Sandbox Code Playgroud)
我需要做些什么来纠正这种情况?
如果它可能是相关的,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;
}
Run Code Online (Sandbox Code Playgroud)
如果你得到的错误是......
无法转换'WhereListIterator
1[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();
Run Code Online (Sandbox Code Playgroud)
对于你的Equals语句永远不是真的问题(由于比较一个总是午夜的日期和一个具有可变时间的日期),尝试获取Date组件,如下所示:
.Where(i => i.WeekOfLastAssignment.Date == currentWeek)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |