我有2个单独的课程列表。 1个列表是当前课程,另一个列表是已过滤课程。我想比较列表,如果课程存在或不存在,我想将FilteredCourse列表上的布尔值标记为true或false。下面是示例代码。
var currentCourses = new List<Course>
{
new Course{CourseNumber = "101", CourseSubject = "ART"},
new Course{CourseNumber = "201", CourseSubject = "BIO"},
new Course{CourseNumber = "301", CourseSubject = "CHEM"},
new Course{CourseNumber = "401", CourseSubject = "CPSC"}
};
var filteredCourses = new List<Course>
{
new Course{CourseNumber = "101", CourseSubject = "ART"},
new Course{CourseNumber = "401", CourseSubject = "CPSC"},
new Course{CourseNumber = "501", CourseSubject = "DANC"},
new Course{CourseNumber = "701", CourseSubject = "HIST"}
};
我尝试过:
foreach (var course in currentCourses)
{
foreach (var filteredCourse in filteredCourses)
{
if ((filteredCourse.CourseNumber === course.CourseNumber) && (filteredCourse.CourseSubject === course.CourseSubject))
{
filteredCourse.AlreadyExists = true;
}
else
{
filteredCourse.AlreadyExists = false;
}
}
}
答案 0 :(得分:1)
您应该在开始时将所有标志设置为false,然后运行循环并仅在找到匹配项时才设置true标志。如果您运行当前的代码,它将遍历所有课程,并且如果匹配的课程不是最后一门课程,则即使将其设置为true,该标志也将始终设置为false。
找到匹配项后,您也可以跳出循环。
类似这样:
foreach (var filteredCourse in filteredCourses)
filteredCourse.AlreadyExists = false;
foreach (var course in currentCourses)
{
foreach (var filteredCourse in filteredCourses)
{
if ((filteredCourse.CourseNumber == course.CourseNumber) && (filteredCourse.CourseSubject == course.CourseSubject))
{
filteredCourse.AlreadyExists = true;
break;
}
}
}
答案 1 :(得分:0)
您可以使用LINQ:
foreach (var f in filteredCourses)
{
f.AlreadyExists = currentCourses.Any(c => (c.CourseNumber == f.CourseNumber
&& c.CourseSubject == f.CourseSubject));
}