Adding filtered data from database into a grid view [closed]

Posted on

Problem

I’m trying to optimize this nested foreach and if statement function for work. My code is retrieving data from a SSMS SQL database with thousands of fields from multiple tables of data, moving them to lists and then looping through the lists to retrieve the data. It is moving all the data to a data grid view to be exported to an excel sheet.

Any ideas on how I can make it run faster?

foreach (Calibrations calibration in Model.PostCalibrationsList)
        {
            if (calibration.Job_No == textBox1.Text)
            {
                foreach (Instruments instrument in Model.InstrumentsList)
                {
                    if (calibration.Inst_ID == instrument.Inst_ID)
                    {
                        foreach (Proc_InstInfo info in Model.Proc_InstInfoList)
                        {
                            foreach (ProcQRef qRef in Model.ProcQRefList)
                            {
                                if (calibration.Inst_ID == instrument.Inst_ID)
                                {
                                    if (instrument.Procedure == info.Proc_No.ToString() && instrument.Procedure == qRef.Procedure.ToString())
                                    {
                                        ex.dataGridView1.Rows.Add(calibration.Order_No, calibration.Inst_ID, instrument.Description, calibration.Cust_Ref, instrument.Manufacturer, instrument.Model_No, instrument.Serial_No, info.Comm1, calibration.Calibration_Required, qRef.StockCode, calibration.Cert_No, info.Proc_No);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

Solution

Given that you say you’re fetching the data from an SQL database, you should use it. It should be much faster to filter the data with a WHERE in the SQL query than to serialise it, deserialise it, and then filter it without the benefit of any indexes.

Given this tiny fragment of code it’s impossible to give more detailed advice on how to do that. It depends enormously on the ORM you’re using.

Leave a Reply

Your email address will not be published. Required fields are marked *