简体   繁体   中英

Compare 2 properties on 2 separate list

I have 2 separate lists of courses. 1 List is of current courses and the other list is of filtered courses. I want to compare the list and if a course exists or it doesn't I want to mark a boolean value on the FilteredCourse list as true or false. Below is sample code.

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"}
        };

I've tried:

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;
                }
            }
        }

You should set all flags to false in the beginning, then run your loop and only set the true flag when a match is found. If you run your current code it will go through all the courses and if the matching one isn't the last one the flag will always be set to false even if it was already set to true.

You can also break out of the loop when a match is found.

So something like:

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;
        }
    }
}

You could use LINQ:

foreach (var f in filteredCourses)
{
  f.AlreadyExists = currentCourses.Any(c => (c.CourseNumber == f.CourseNumber 
    && c.CourseSubject == f.CourseSubject));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM