zoukankan      html  css  js  c++  java
  • 将两个列不同的DataTable合并成一个新的DataTable

       /// <summary>
            /// 将两个列不同(结构不同)的DataTable合并成一个新的DataTable
            /// </summary>
            /// <param name="DataTable1">表1</param>
            /// <param name="DataTable2">表2</param>
            /// <returns>合并后的新表</returns>
            private DataTable UniteDataTable(DataTable DataTable1, DataTable DataTable2)
            {
                //克隆DataTable1的结构
                DataTable newDataTable = DataTable1.Clone();
                for (int i = 0; i < DataTable2.Columns.Count; i++)
                {
                    //再向新表中加入DataTable2的列结构
                    newDataTable.Columns.Add(DataTable2.Columns[i].ColumnName);
                }
                object[] obj = new object[newDataTable.Columns.Count];
                //添加DataTable1的数据
                for (int i = 0; i < DataTable1.Rows.Count; i++)
                {
                    DataTable1.Rows[i].ItemArray.CopyTo(obj, 0);
                    newDataTable.Rows.Add(obj);
                }

                if (DataTable1.Rows.Count >= DataTable2.Rows.Count)
                {
                    for (int i = 0; i < DataTable2.Rows.Count; i++)
                    {
                        for (int j = 0; j < DataTable2.Columns.Count; j++)
                        {
                            newDataTable.Rows[i][j + DataTable1.Columns.Count] = DataTable2.Rows[i][j].ToString();
                        }
                    }
                }
                else
                {
                    DataRow dr3;
                    //向新表中添加多出的几行
                    for (int i = 0; i < DataTable2.Rows.Count - DataTable1.Rows.Count; i++)
                    {
                        dr3 = newDataTable.NewRow();
                        newDataTable.Rows.Add(dr3);
                    }
                    for (int i = 0; i < DataTable2.Rows.Count; i++)
                    {
                        for (int j = 0; j < DataTable2.Columns.Count; j++)
                        {
                            newDataTable.Rows[i][j + DataTable1.Columns.Count] = DataTable2.Rows[i][j].ToString();
                        }
                    }
                }
                return newDataTable;
            }
            #endregion

  • 相关阅读:
    Jqeury ajax 调用C#的后台程序
    电商设计1
    智能分类
    网络爬虫框架Webmagic
    Spring Cloud 微服务架构解决方案
    网站流量日志数据分析系统1
    Shell 编程
    Zookeeper
    网站流量日志数据自定义采集
    分库分表的面试题5
  • 原文地址:https://www.cnblogs.com/peace-lee/p/3298008.html
Copyright © 2011-2022 走看看