I am Working on a MVC4 project and I am in need to create a new list of objects by comparing two lists. db below refers to the DbContext object.
In the project that I work, I am in need of comparing two lists. The first has all the subjects offered in a semester. The other has the subjects selected by the student.
List<Subject> subjects = db.Subjects;
//...
List<Subject> semesterSubjects = student.Subjects;
Out of this two lists I need to create a list of items that state if or not each an every item is selected. It looks like this.
class SubjectSelection
{
public int ID { get; set; }
public String Title { get; set; }
public bool IsSelected { get; set; }
}
What I need now is to compare subjects & semesterSubjects and get a IEnumerable<SubjectSelection>
Could I use Linq to get such a result and how?
Best way is to do this job on the server side. Select ids from your semester subjects:
And pass them to query:
If you are using same db context instance to retrieve both semester subjects list and subjects list, then you can simply use:
Entity Framework implements identity map pattern, which means it returns same in-memory instance of subject object, which returned by different queries.