日期:2011-05-31  浏览次数:20517 次

在下面的例子中实现了3个Join方法,其目的是把两个DataTable连接起来,相当于Sql的Inner Join方法,返回DataTable的所有列。
如果两个DataTable中的DataColumn有重复的话,把第二个设置为ColumnName+"_Second",下面是代码,希望对大家有所帮助。
using System;
using System.Data;

namespace WindowsApplication1
{
    public class SQLOps
    {
        public SQLOps()
        {           
        }

        public static DataTable Join (DataTable First, DataTable Second, DataColumn[] FJC, DataColumn[] SJC)

        {

            //创建一个新的DataTable

            DataTable table = new DataTable("Join");


            // Use a DataSet to leverage DataRelation

            using(DataSet ds = new DataSet())

            {

                //把DataTable Copy到DataSet中

                ds.Tables.AddRange(new DataTable[]{First.Copy(),Second.Copy()});

                DataColumn[] parentcolumns = new DataColumn[FJC.Length];

                for(int i = 0; i < parentcolumns.Length; i++)

                {

                    parentcolumns[i] = ds.Tables[0].Columns[FJC[i].ColumnName];

                }

                DataColumn[] childcolumns = new DataColumn[SJC.Length];

                for(int i = 0; i < childcolumns.Length; i++)

                {

                    childcolumns[i] = ds.Tables[1].Columns[SJC[i].ColumnName];

                }


                //创建关联

                DataRelation r = new DataRelation(string.Empty,parentcolumns,childcolumns,false);

                ds.Relations.Add(r);


                //为关联表创建列

                for(int i = 0; i < First.Columns.Count; i++)

                {

                    table.Columns.Add(First.Columns[i].Col