DataTable交叉口操作

时间:2009-04-07 10:21:44

标签: datatable

我有两个像这样定义的数据表;

Dim db1,db2 As New DataTable

db1和db2保存来自不同查询的结果,但两者中的列完全相同。我想创建另一个数据表,其中包含db1和db2中的记录。即我想要两个数据表的交集。有一个简单的方法吗?

(结果数据表将用于填充网格视图。)

2 个答案:

答案 0 :(得分:2)

你可以这样试试。

        // Declare Data Table and Data View
        DataTable dt1 = new DataTable();
        DataTable dt2 = new DataTable();
        DataTable dt3 = new DataTable();
        DataTable dtTemp = new DataTable();
        DataView dv = new DataView();

        dt1.Columns.Add("Col1");
        dt1.Columns.Add("Col2");
        dt1.Columns.Add("Col3");

        dt2.Columns.Add("Col1");
        dt2.Columns.Add("Col2");
        dt2.Columns.Add("Col3");

        // Initialize Data Table and Data View

        dt1.Rows.Add("A", "B", "C"); // Testing data for data table 1; actual data will come from your query
        dt1.Rows.Add("E", "F", "G"); //                                 ==

        dt2.Rows.Add("A", "B", "C");
        dt2.Rows.Add("U", "V", "W");// Testing data for data table 2; actual data will come from your query
        dt2.Rows.Add("X", "Y", "Z");//                                  ==


        // Merge Data Table into temporary Data Table
        dtTemp = dt1;  //Initialize dt1 value in to dtTemp
        dtTemp.Merge(dt2);// Merge it with dt2 you will get the 

        // Use Data View to get disticnt values
        dv = new DataView(dtTemp);
        dt3 = dv.ToTable(true, "Col1", "Col2", "Col3");// Remember, it is for intersection not for union 

答案 1 :(得分:0)

如果您使用VB.NET with LINQ,可以这样做:

Dim db3 = db1.Intersect(db2)

从那里只需使用db3填充GridView。