比较数据表 [英] Compare datatables

查看:90
本文介绍了比较数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立从数据库中显示的记录中的窗口和检查新记录每两秒钟的数据库的应用程序。问题是,窗口中的每个检查新记录的时间闪烁,我想解决它。我试图旧数据表用新的比较和刷新,只有当他们是不同的。
有谁知道什么是这种情况下,最好的做法?我试着做以下方式,但它不工作:

 私人布尔GetBelongingMessages()
$ { b $ b布尔结果= FALSE;
的DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID);
如果(dtTemp = dtMessages!)
{
dtMessages = dtTemp;
结果=真;
}
,否则
{
结果= FALSE;
}
返回结果;
}


解决方案

首先,它是重要的认识到什么你在你的代码比较是的引用的数据表中的数据表,而不是的内容的的。为了确定两个数据表具有相同的内容,你要通过所有的行和列的有循环,看看他们是平等的:

  //这是假设数据表具有相同的架构... 
公共BOOL DatatablesAreSame(数据表T1,T2数据表){
如果(t1.Rows.Count!= t2.Rows.Count)
返回false;

的foreach(在t1.Columns的DataColumn DC){
的for(int i = 0; I< t1.Rows.Count;我++){$​​ B $ B如果(t1.Rows ![I] [dc.ColumnName] = t2.Rows [I] [dc.ColumnName]){
返回false;
}
}
}
返回真;
}


I built an application which displays the records from database in the window and checks the the database for new records every couple of seconds. The problem is that the window blinks each time I check for new records and I want to fix it. I have tried to compare the old datatable with the new one and refresh only if they are different. Does anyone know what is the best practice for such cases? I tried to do it the following way but it doesn't work:

private bool GetBelongingMessages()
        {
            bool result = false;
            DataTable dtTemp = OleDbWorks.GetBelongingMessages(currentCallID);
            if(dtTemp != dtMessages)
            {
                dtMessages = dtTemp;
                result = true;
            }
            else
            {
                result = false;
            }
            return result;
        }

解决方案

First off, it's important to recognize that what you're comparing in your code is the references of the datatables, not the contents of the datatables. In order to determine if both datatables have the same contents, you're going to have to loop through all of the rows and columns and see if they're equal:

//This assumes the datatables have the same schema...
        public bool DatatablesAreSame(DataTable t1, DataTable t2) {         
            if (t1.Rows.Count != t2.Rows.Count)
                return false;

            foreach (DataColumn dc in t1.Columns) {
                for (int i = 0; i < t1.Rows.Count; i++) {
                    if (t1.Rows[i][dc.ColumnName] != t2.Rows[i][dc.ColumnName]) {
                        return false;
                    }
                }
            }
            return true;
        }

这篇关于比较数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆