c# - Proper way to loop a SQL Query? -
i have list retrieves student's grades passing in list of student class,
it pulls student grades querying student's name through database. code works fine however, when studentlist increases in size, code gets slow execute,
what proper method looping list through sql query?
private list<studentclass> getstudentgrades(list<studentclass> studentlist) { (int =0; < studentlist.count; i++) { string sqlcommand = "select studentgrades students studentname=@studentname"; conn.open(); using (sqlcommand cmd = new sqlcommand(sqlcommand, conn)) { cmd.parameters.addwithvalue("@studentname", studentlist[i].studentname); cmd.executenonquery(); sqldatareader reader = cmd.executereader(); while (reader.reader()) { studentlist[i].studentgrades = int.parse(reader["studentgrades"].tostring()); } } } return studentlist; } public class studentclass { public string studentname {get; set; } public int studentgrades {get; set; } }
first of - you're unnecessary executing command twice. you're calling executenonquery
first (it has no effect since executenonquery
doesn't returns data, slows down execution since request being passed sql server , being executed). you're calling executereader
you're retrieving data.
second issue - you're executing new query each student. if have 1000 students in list - 1000 queries executed.
consider getting data database first, , update studentlist
accordingly.
something getting select studentname, studentgrades students
first, save result dictionary (or wherever want) , loop on studentlist
Comments
Post a Comment