我有这个if else语句,可以在ExamController.cs上很好地运行,但是我想使用switch语句使它更易于阅读。我添加到switch语句的唯一一件事就是ExamId。
如果else语句起作用但我的切换情况不起作用,这怎么会这样。错误与退货有关,但是我没有对退货进行任何更改。
if (model.SearchType == "School")
{
result = FindExams((e) => e.School.School_Name.Contains(model.SearchInput));
}
else if (model.SearchType == "Exam Date")
{
result = FindExams((e) => e.Exam.ExamDate >= model.StartDate.Date && e.Exam.ExamDate <= model.EndDate.Date);
}
else if (model.SearchType == "District")
{
result = FindExams((e) => e.District.Name.Contains(model.SearchInput));
}
else if (model.SearchType == "ID")
{
result = FindExams((e) => e.Student.ID.Contains(model.SearchInput));
}
else if (model.SearchType == "First Name")
{
result = FindExams((e) => e.Student.FirstName.Contains(model.SearchInput));
}
else if (model.SearchType == "Last Name")
{
result = FindExams((e) => e.Student.LastName.Contains(model.SearchInput));
}
return result.OrderByDescending(r => r.ExamDate);
切换语句
switch (model.SearchType)
{
case "School":
result = this.FindExams((e) => e.School.School_Name.Contains(model.SearchInput));
break;
case "ExamDate":
result = FindExams((e) => e.Exam.ExamDate >= model.StartDate.Date && e.Exam.ExamDate <= model.EndDate.Date);
break;
case "District":
result = this.FindExams((e) => e.District.Name.Contains(model.SearchInput));
break;
case "ID":
result = this.FindExams((e) => e.Student.ID.Contains(model.SearchInput));
break;
case "First Name":
result = this.FindExams((e) => e.Student.FirstName.Contains(model.SearchInput));
break;
case "Last Name":
result = this.FindExams((e) => e.Student.LastName.Contains(model.SearchInput));
break;
case "Exam Id":
int examId = int.Parse(model.SearchInput);
result = this.FindExams((e) => e.Exam.Exam_Id == examId);
break;
}
return result.OrderByDescending(r => r.ExamDate);
答案 0 :(得分:0)
这两个代码段在以下几行不同:
else if (model.SearchType == "Exam Date")
和
case "ExamDate":
如您所见,它们检查两个不同的字符串。 应该是:
case "Exam Date":