sql server - C# Entity Framework: Mapping select results to list of objects -
let's have list of student objects , want find tuition. tuition in database , key student id. want map tuition student objects after. have
class student{ int id; string name; double gpa; double tuition; }
example database tuple |id | tuition | schoolname| student name|
list<double> gettuitionsbyid(list<student> students) { var ids = students.select(x => x.id).tolist(); var query = dbstudent in _context.studentsdb ids.contains(dbstudent.id) select dbstudent.tuition; var tuitions = query.tolist(); return tuitions; }
i hoping loop through tuitions
, map students list, select query doesn't return prices in same order. how can map tuitions db student objects?
when have no ordering in database query results coming database not guaranteed in specific order. return results in order passed in need return id
database data can mapped initial list , create list manually:
list<double> gettuitionsbyid(list<student> students) { var ids = students.select(x => x.id).tolist(); // return id , tuition var query = dbstudent in _context.studentsdb ids.contains(dbstudent.id) select new { dbstudent.id, dbstudent.tuition}; var tuitions = query.tolist(); var results = list<double>(); foreach(var student in students) { // below assumed every student has tuition returned database var foundtuition = tuitions.first(t => t.id == student.id); results.add(foundtuition.tuition); } return results; }
edit: @pwas correctly pointed out using dictionary
give better performance:
list<double> gettuitionsbyid(list<student> students) { var ids = students.select(x => x.id).tolist(); // return id , tuition var query = dbstudent in _context.studentsdb ids.contains(dbstudent.id) select new { dbstudent.id, dbstudent.tuition}; var tuitions = query.asenumerable().todictionary(s => s.id, s => x.tuition); var results = list<double>(); foreach(var student in students) { // below assumed every student has tuition returned database results.add(tuitions[student.id]); } return results; }
Comments
Post a Comment