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:
var selectedIDs = semesterSubjects.Select(s => s.ID).ToList();
And pass them to query:
var query = db.Subjects.Select(s => new SubjectSelection()
{
ID = s.ID,
Title = s.Title,
IsSelected = selectedIDs.Contains(s.ID)
});
If you are using same db context instance to retrieve both semester subjects list and subjects list, then you can simply use:
var query = subjects.Select(s => new SubjectSelection()
{
ID = s.ID,
Title = s.Title,
IsSelected = semesterSubjects.Contains(s)
});
Entity Framework implements identity map pattern, which means it returns same in-memory instance of subject object, which returned by different queries.
var allSubjectsWithSelection = subjects.Select(o=>new SubjectSelection(){ID = o.ID,Title = o.Title, IsSelected = semesterSubjects.Any(s=>s.ID == o.ID)}).ToList();
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.