Click here to Skip to main content
15,120,268 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi experts,

I need your help in below regards. I have a table Name: "Persons", having multiple fields including ID, PersonID, Name etc.
To retrieve table data, I am firing "Select * from Persons" and setting values to dataset and binding it to Grid DataSource. Now I want to remove few PersonId from these list.
So for that I have created a list "listRecords" and adding those PersonID to this list. After that I have created a loop like below and removed items when PersonID matches. It's working fine but it's complexity is high, as I am creating a loop on List and then comparing to dataset table value.
I need your help to optimize it.
C#
if (listRecords != null && listRecords.Count > 0)
                    {
                        foreach (string item in listRecords)
                        {
                            for (int i = 0; i < dataset.Tables[0].Rows.Count; i++)
                            {                                
                                if (item.Equals(dataset.Tables[0].Rows[i]["PersonID"], StringComparison.InvariantCultureIgnoreCase))
                                {
                                    dataset.Tables[0].Rows.Remove(dataset.Tables[0].Rows[i]);
                                }
                            }

                        }
                    }					
					grid.DataSource = dataset.Tables[0].DefaultView;

Thanks,

What I have tried:

Above mentioned code is working fine, which I have tried.
Posted
Updated 15-Aug-20 8:52am
Comments
[no name] 15-Aug-20 13:26pm
   
How is about to fire an SQL DELETE FROM PERSONS WHERE PersonId = :PersonIdand afterwards refresh your SELECT *...?
User-8621695 15-Aug-20 13:30pm
   
Thanks, but I don't have to make SQL call with delete operation,as I am doing few more operations on data and then removing it.
[no name] 15-Aug-20 14:03pm
   
Sorry. I see now, I was completely wrong.

Try:
SQL
SELECT * FROM Persons WHERE PersonID NOT IN (... list of unwanted IDs ...)
   
Comments
Dave Kreskowiak 15-Aug-20 13:51pm
   
And get rid of the * in the SELECT.

Sorry, it's a pet peeve of mine.
OriginalGriff 15-Aug-20 13:57pm
   
And mine - but I have no idea what the columns are.
First, as Griff says, do as much work within the database as you can.

Second, avoid foreach loop when a for loop will suffice.

Third, use the DataTable.DefaultView to filter (and sort) the rows in the table when you can.

Fourth, don't refer to columns by name within a loop -- use the ordinal.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900