如何在2个数据表中进行比较? [英] How to compare in 2 data tables?

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

问题描述

我有2个数据表.每个数据表都有"ID"列.我想获取两个数据表中都存在的那些ID.
我应该怎么做.
我还需要将提取的行放在新的数据表中.该怎么办?

I have 2 datatables.each of them has column "ID".I want to get those IDs that are present in both datatables.
How should i do it.
i also need to put the extracted rows in a new datatable.how do i do that?

推荐答案

嘿,

您会得到如下的常见ID

DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
dt.Rows.Add(4);
DataTable dt1 =新的DataTable();
dt1.Columns.Add("ID");

dt1.Rows.Add(1);
dt1.Rows.Add(2);
dt1.Rows.Add(3);



foreach(在dt.rows中的DataRow dr)
{
foreach(dt1.Rows中的DataRow dr1)
{
如果(dr [0] .ToString()== dr1 [0] .ToString())
Response.Write(dr [0] .ToString());
}
}

祝你好运
快乐编码
hey,

u get common ids like following

DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
dt.Rows.Add(4);
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID");

dt1.Rows.Add(1);
dt1.Rows.Add(2);
dt1.Rows.Add(3);



foreach (DataRow dr in dt.Rows)
{
foreach (DataRow dr1 in dt1.Rows)
{
if (dr[0].ToString() == dr1[0].ToString())
Response.Write(dr[0].ToString());
}
}

Best Luck
Happy Coding


这是一种有效的步行方式.如果使用foreach,则随着表的增大,您将把时间增加平方(O(x square)).该解决方案是线性的(O(x)):

This is a walk which is effecient. If you use the foreach, as the tables get larger you increase the time by the square (O(x square)). This solution is linear (O(x)):

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
int c1 = 0;
int c2 = 0;

while (c1 < dt1.Rows.Count  && c2 < dt2.Rows.Count)
{
    if ((int)dt1.Rows[c1][0] == (int) dt1.Rows[c2][0])
    {
        //Match found
        c1++;
        c2++;
    }
    else if ((int)dt1.Rows[c1][0] > (int)dt1.Rows[c2][0])
    {
        //Missing row in dt1
        c2++;
    }
    else
    {
        //Missing row in dt2
        c1++;
    }
}

if (c1 < dt1.Rows.Count)
{
    //Missing rows at the end in dt2
}
if (c2 < dt2.Rows.Count)
{
    //Missing rows at the end in dt1
}



如果要在表中显示结果,则:



If you want to have the results in a table then:

dt3.Rows.Add(dt1.Rows[c1]);



dt3是您定义的另一个表.



Where dt3 is another table you have defined.


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

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