DataTable表连接
Posted kexb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataTable表连接相关的知识,希望对你有一定的参考价值。
public static System.Data.DataTable TableJoin(System.Data.DataTable dt, System.Data.DataTable dtDetail, string[] parentFieldName, string[] relationFieldName, bool isInnerJoin, string relationName = "") { System.Data.DataTable joinDt = new System.Data.DataTable(); try { using (DataSet ds = new DataSet()) { ds.Tables.AddRange(new System.Data.DataTable[] { dt, dtDetail }); if (string.IsNullOrEmpty(relationName)) { relationName = Guid.NewGuid().ToString(); } List<DataColumn> parentc = new List<DataColumn>(); List<DataColumn> childc = new List<DataColumn>(); foreach (var item in parentFieldName) { parentc.Add(dt.Columns[item]); } foreach (var item in relationFieldName) { childc.Add(dtDetail.Columns[item]); } DataRelation relation = new DataRelation(relationName, parentc.ToArray(), childc.ToArray(), false); ds.Relations.Add(relation); for (int i = 0; i < dt.Columns.Count; i++) { joinDt.Columns.Add(dt.Columns[i].ColumnName, dt.Columns[i].DataType); } for (int i = 0; i < dtDetail.Columns.Count; i++) { joinDt.Columns.Add(dtDetail.Columns[i].ColumnName, dtDetail.Columns[i].DataType); } joinDt.BeginLoadData(); foreach (DataRow firstrow in ds.Tables[0].Rows) { //得到行的数据 DataRow[] childrows = firstrow.GetChildRows(relation); object[] parentarray = firstrow.ItemArray; if (childrows != null && childrows.Length > 0) { foreach (DataRow childrow in childrows) { object[] childarray = childrow.ItemArray; object[] joinarray = new object[parentarray.Length + childarray.Length]; Array.Copy(parentarray, 0, joinarray, 0, parentarray.Length); Array.Copy(childarray, 0, joinarray, parentarray.Length, childarray.Length); joinDt.LoadDataRow(joinarray, true); } } else { if (!isInnerJoin) { joinDt.LoadDataRow(parentarray, true); } } } joinDt.EndLoadData(); } } catch (Exception ex) { throw ex; } return joinDt; }
以上是关于DataTable表连接的主要内容,如果未能解决你的问题,请参考以下文章
c# 如何将多个单行多列的datatable合并成一个单行多列的datatable,表中内容是string..