dataset 中 datatable 关联查询

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DataSetHelper
{
    public class DataSetHelper
    {
        public DataSet ds;
        private System.Collections.ArrayList m_FieldInfo; private string m_FieldList;
        private class FieldInfo
        {
            public string RelationName;
            public string FieldName; //source table field name
            public string FieldAlias; //destination table field name
         
        }

        public DataSetHelper(ref DataSet DataSet)
        {
            ds = DataSet;
        }
        public DataSetHelper()
        {
            ds = null;
        }
        private void ParseFieldList(string FieldList, bool AllowRelation)
        {
            /*
             * This code parses FieldList into FieldInfo objects  and then
             * adds them to the m_FieldInfo private member
             *
             * FieldList systax:  [relationname.]fieldname[ alias], ...
            */
            if (m_FieldList == FieldList) return;
            m_FieldInfo = new System.Collections.ArrayList();
            m_FieldList = FieldList;
            FieldInfo Field; string[] FieldParts;
            string[] Fields = FieldList.Split(',');
            int i;
            for (i = 0; i <= Fields.Length - 1; i++)
            {
                Field = new FieldInfo();
                //parse FieldAlias
                FieldParts = Fields[i].Trim().Split(' ');
                switch (FieldParts.Length)
                {
                    case 1:
                        //to be set at the end of the loop
                        break;
                    case 2:
                        Field.FieldAlias = FieldParts[1];
                        break;
                    default:
                        throw new Exception("Too many spaces in field definition: '" + Fields[i] + "'.");
                }
                //parse FieldName and RelationName
                FieldParts = FieldParts[0].Split('.');
                switch (FieldParts.Length)
                {
                    case 1:
                        Field.FieldName = FieldParts[0];
                        break;
                    case 2:
                        if (AllowRelation == false)
                            throw new Exception("Relation specifiers not permitted in field list: '" + Fields[i] + "'.");
                        Field.RelationName = FieldParts[0].Trim();
                        Field.FieldName = FieldParts[1].Trim();
                        break;
                    default:
                        throw new Exception("Invalid field definition: " + Fields[i] + "'.");
                }
                if (Field.FieldAlias == null)
                    Field.FieldAlias = Field.FieldName;
                m_FieldInfo.Add(Field);
            }
        }

        public DataTable CreateJoinTable(string TableName, DataTable SourceTable, string FieldList)
        {
            /*
             * Creates a table based on fields of another table and related parent tables
             *
             * FieldList syntax: [relationname.]fieldname[ alias][,[relationname.]fieldname[ alias]]...
            */
            if (FieldList == null)
            {
                throw new ArgumentException("You must specify at least one field in the field list.");
                //return CreateTable(TableName, SourceTable);
            }
            else
            {
                DataTable dt = new DataTable(TableName);
                ParseFieldList(FieldList, true);
                foreach (FieldInfo Field in m_FieldInfo)
                {
                    if (Field.RelationName == null)
                    {
                        DataColumn dc = SourceTable.Columns[Field.FieldName];
                        dt.Columns.Add(dc.ColumnName, dc.DataType, dc.Expression);
                    }
                    else
                    {
                        DataColumn dc = SourceTable.ParentRelations[Field.RelationName].ParentTable.Columns[Field.FieldName];
                        dt.Columns.Add(dc.ColumnName, dc.DataType, dc.Expression);
                    }
                }
                if (ds != null)
                    ds.Tables.Add(dt);
                return dt;
            }
        }

        public void InsertJoinInto(DataTable DestTable, DataTable SourceTable,
    string FieldList, string RowFilter, string Sort)
        {
            /*
            * Copies the selected rows and columns from SourceTable and inserts them into DestTable
            * FieldList has same format as CreatejoinTable
            */
            if (FieldList == null)
            {
                throw new ArgumentException("You must specify at least one field in the field list.");
                //InsertInto(DestTable, SourceTable, RowFilter, Sort);
            }
            else
            {
                ParseFieldList(FieldList, true);
                DataRow[] Rows = SourceTable.Select(RowFilter, Sort);
                foreach (DataRow SourceRow in Rows)
                {
                    DataRow DestRow = DestTable.NewRow();
                    foreach (FieldInfo Field in m_FieldInfo)
                    {
                        if (Field.RelationName == null)
                        {
                            DestRow[Field.FieldName] = SourceRow[Field.FieldName];
                        }
                        else
                        {
                            DataRow ParentRow = SourceRow.GetParentRow(Field.RelationName);
                            DestRow[Field.FieldName] = ParentRow[Field.FieldName];
                        }
                    }
                    DestTable.Rows.Add(DestRow);
                }
            }
        }

        public DataTable SelectJoinInto(string TableName, DataTable SourceTable, string FieldList, string RowFilter, string Sort)
        {
            /*
             * Selects sorted, filtered values from one DataTable to another.
             * Allows you to specify relationname.fieldname in the FieldList to include fields from
             *  a parent table. The Sort and Filter only apply to the base table and not to related tables.
            */
            DataTable dt = CreateJoinTable(TableName, SourceTable, FieldList);
            InsertJoinInto(dt, SourceTable, FieldList, RowFilter, Sort);
            return dt;
        }
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                         调用 winform
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataSetHelper;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DataSet ds; DataSetHelper.DataSetHelper dsHelper;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ds = new DataSet();
            dsHelper = new DataSetHelper.DataSetHelper(ref ds);
            //Create source tables
            DataTable dt = new DataTable("Employees");
            dt.Columns.Add("EmployeeID", Type.GetType("System.Int32"));
            dt.Columns.Add("FirstName", Type.GetType("System.String"));
            dt.Columns.Add("LastName", Type.GetType("System.String"));
            dt.Columns.Add("BirthDate", Type.GetType("System.DateTime"));
            dt.Columns.Add("JobTitle", Type.GetType("System.String"));
            dt.Columns.Add("DepartmentID", Type.GetType("System.Int32"));
            dt.Rows.Add(new object[] { 1, "Tommy", "Hill", new DateTime(1970, 12, 31), "Manager", 42 });
            dt.Rows.Add(new object[] { 2, "Brooke", "Sheals", new DateTime(1977, 12, 31), "Manager", 23 });
            dt.Rows.Add(new object[] { 3, "Bill", "Blast", new DateTime(1982, 5, 6), "Sales Clerk", 42 });
            dt.Rows.Add(new object[] { 1, "Kevin", "Kline", new DateTime(1978, 5, 13), "Sales Clerk", 42 });
            dt.Rows.Add(new object[] { 1, "Martha", "Seward", new DateTime(1976, 7, 4), "Sales Clerk", 23 });
            dt.Rows.Add(new object[] { 1, "Dora", "Smith", new DateTime(1985, 10, 22), "Trainee", 42 });
            dt.Rows.Add(new object[] { 1, "Elvis", "Pressman", new DateTime(1972, 11, 5), "Manager", 15 });
            dt.Rows.Add(new object[] { 1, "Johnny", "Cache", new DateTime(1984, 1, 23), "Sales Clerk", 15 });
            dt.Rows.Add(new object[] { 1, "Jean", "Hill", new DateTime(1979, 4, 14), "Sales Clerk", 42 });
            dt.Rows.Add(new object[] { 1, "Anna", "Smith", new DateTime(1985, 6, 26), "Trainee", 15 });
            ds.Tables.Add(dt);

            dt = new DataTable("Departments");
            dt.Columns.Add("DepartmentID", Type.GetType("System.Int32"));
            dt.Columns.Add("DepartmentName", Type.GetType("System.String"));
            dt.Rows.Add(new object[] { 15, "Men's Clothing" });
            dt.Rows.Add(new object[] { 23, "Women's Clothing" });
            dt.Rows.Add(new object[] { 42, "Children's Clothing" });
            ds.Tables.Add(dt);

            ds.Relations.Add("DepartmentEmployee", ds.Tables["Departments"].Columns["DepartmentID"],
                ds.Tables["Employees"].Columns["DepartmentID"]);

        }

        private void btnCreateJoin_Click(object sender, EventArgs e)
        {
            dsHelper.CreateJoinTable("EmpDept", ds.Tables["Employees"],
    "FirstName FName,LastName LName,BirthDate,DepartmentEmployee.DepartmentName Department");
            //dataGrid1.SetDataBinding(ds, "EmpDept");
        }

        private void btnSelectJoinInto_Click(object sender, EventArgs e)
        {
            dsHelper.SelectJoinInto("EmpDept2", ds.Tables["Employees"],
    "FirstName,LastName,BirthDate BDate,DepartmentEmployee.DepartmentName Department",
    "JobTitle='Manager'", "DepartmentID");
            //dataGrid1.SetDataBinding(ds, "EmpDept2");

        }

        private void btnInsertJoinInto_Click(object sender, EventArgs e)
        {
            dsHelper.InsertJoinInto(ds.Tables["EmpDept"], ds.Tables["Employees"],
    "FirstName FName,LastName LName,BirthDate,DepartmentEmployee.DepartmentName Department",
    "JobTitle='Sales Clerk'", "DepartmentID");
           
            //dataGrid1.SetDataBinding(ds, "EmpDept");
           
    

        }
    }
}




 

原文地址:https://www.cnblogs.com/xianzuoqiaoqi/p/1539477.html