C#中DataTable删除多条数据

 //一般情况下我们会这么删除

                DataTable dt = new DataTable();

                for (int i = 0; i < dt.Rows.Count; i++)

                {

                    if (99 % i == 0)

                    {

                        dt.Rows.RemoveAt(i);

                    }

                }

                //但是这么删除会出现意外情况

                //当运行dt.Rows.RemoveAt(i)代码后DataTable的index会发生改变

                //且他的dt.Rows.Count也会改变

                //正确做法一

                for (int i = dt.Rows.Count - 1; i >= 0; i--)

                {

                    if (99 % i == 0)

                    {

                        dt.Rows.RemoveAt(i);

                    }

                }

                //正确做法二

                for (int i = 0; i < dt.Rows.Count; i++)

                {

                    if (99 % i == 0)

                    {

                        dt.Rows[i].Delete();

                    }

                }

                dt.AcceptChanges();//提交

                //dt.RejectChanges();//回滚个人笔记

posted @ 2018-07-18 16:27  z_handsome  阅读(3787)  评论(1编辑  收藏  举报