Q: SelectListItem checkboxes and autopopulate with using Contains() I have a list of courses.  If a user is assigned to a course, then I want that checkbox to be checked.  How come the Contains() is not accepted?
ViewModel:
public class ViewUserViewModel
{        
    public List<Cours> Courses { get; set; }
    public List<UserCours> UserCoursesList { get; set; }        
    public AspNetUser user { get; set; }
    public IEnumerable<SelectListItem> CourseList { get; set; }
}

Controller:
[HttpGet]
public ActionResult ViewUser(string id)
{
    ViewUserViewModel model = new ViewUserViewModel();

    model.user = db.AspNetUsers.FirstOrDefault(U => U.Id == id);

    //List all courses
    List<Cours> allCourses = db.Courses.OrderBy(c => c.CourseName).ToList();
    model.Courses = allCourses;

    //List of courses the user is assigned to
    //var selectedCourse1 = db.UserCourses.Where(uc => uc.UserId == id).ToList();
    model.UserCoursesList = db.UserCourses.Where(uc => uc.UserId == id).ToList();

    //checkbox list
    model.CourseList = allCourses.ToList().Select(x => new SelectListItem()
    {
          //Selected = selectedCourse1.Contains(x.CourseID),
          Selected = model.UserCoursesList.Contains(x.CourseID),
          Text = x.CourseName,
          Value = x.CourseID.ToString()
     });

  }

I'm thinking the Selected property will test if List has the value assigned, then it would return back true.  Instead, it's a syntax error and has invalid arguments.  How can I compare the CourseList to the UserCoursesList?

A: I think you should use LINQ Any method. You not posted you UserCours class definition, but I guess that it should have an ID, and might look like that:
public class Cours
{
    public int Id { get; set; }
    // Other properties
}

In this case your check for Selected property will be:
Selected = model.UserCoursesList.Any(uc => uc.CourseID == x.CourseID) 

Some tips:


*

*In this case it will be better to use some meaningful name instead of
x, for example course. It will improve readability of the code.

*allCourses is already a list, you do not need to call ToList()
method again.


A: Updated code: thanks to Aleksandr
[HttpGet]
public ActionResult ViewUser(string id)
{
    ViewUserViewModel model = new ViewUserViewModel();

    //Which user
    model.user = db.AspNetUsers.FirstOrDefault(User => User.Id == id);

    //List all courses
    model.Courses = db.Courses.OrderBy(Courses => Courses.CourseName).ToList();

    //List of courses the user is assigned to
    model.UserCoursesList = db.UserCourses.Where(UserCourses => UserCourses.UserId == id).ToList();

    //checkbox list
    model.CourseList = model.Courses.Select(Course => new SelectListItem()
    {
           Selected = model.UserCoursesList.Any(UserCourse => UserCourse.CourseId == Course.CourseID),
           Text = Course.CourseName,
           Value = Course.CourseID.ToString()
    });
    return View(model);
}

