none
Deleting Rows Conditionally From a DataTable RRS feed

  • Question

  • I am trying to go one by one, comparing rows in a sorted DataTable. The rows are in order by store number, and then by date and time. What I need is if the store number is the same, and the percent is the same, the record is considered obsolete and I need to delete the DataRow from the Data Table. If the percent changes however, I need to keep that row and I also need to keep the data row previous to that one and I need to also keep the next consecutive one. 

    For example. if my table was like this:

    [1] 0

    [2] 0

    [3] 3

    [4] 0

    [5] 0

    I would want to keep rows 2, 3, and 4. In my current code, each data row looks like this:

    Store number [col 0], online [1], offline [2], percent [3], datetime[4]. 

    This is my current code as of right now: 

     public DataTable DeleteFromDataTable(DataTable dt)
            {
                dt.AcceptChanges();
                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    DataRow dr1 = dt.Rows[i-1];
                    DataRow dr2 = dt.Rows[i];
                    
    
                    //StoreNumber and Percent are the same
                    if (dr2[0].Equals(dr1[0]) && dr2[3] == dr1[3])
                    {
                        //Delete first in comparison
                        dt.Rows[i - 1].Delete();
                    }
                }
    
                return dt;
            }

    But it does not work the way I want it. As of right now, it appears to delete a majority of the records i need gone but it only keeps the previous record and then the one that is actually changing, I need to keep the next consecutive one as well. Also, sometimes it doesn't delete chains of rows that don't have a changing percent. 

    I would post pictures as great examples of what I mean but my account is not verified.

    Wednesday, July 18, 2018 3:43 PM

All replies

  • I think it remains still unclear what you mean. How about conflict scenarios between those two rules of yours?

    One problem I see is that your second rule calls for retaining the rows immediately previous and after the respective DataRow and so might affect rows that need to be deleted following your first rule. This might be the reason for the failure of your method because it implements only rule 1), but ignores rule 2).
    How do you solve such conflicts?
    Thursday, July 19, 2018 7:28 PM