Join two DataTables in C#
var query = (from x in a.AsEnumerable()
join y in b.AsEnumerable() on x.Field<int>("col1") equals y.Field<int>("col1")
select new { col1= y.Field<int>("col1"), col2=x.Field<int>("col2") }).ToList();
DataTableHelper
public static class DataTableHelper
{
public enum JoinType
{
/// <summary>
/// Same as regular join. Inner join produces only the set of records that match in both Table A and Table B.
/// </summary>
Inner = ,
/// <summary>
/// Same as Left Outer join. Left outer join produces a complete set of records from Table A, with the matching records (where available) in Table B. If there is no match, the right side will contain null.
/// </summary>
Left =
} /// <summary>
/// Joins the passed in DataTables on the colToJoinOn.
/// <para>Returns an appropriate DataTable with zero rows if the colToJoinOn does not exist in both tables.</para>
/// </summary>
/// <param name="dtblLeft"></param>
/// <param name="dtblRight"></param>
/// <param name="colToJoinOn"></param>
/// <param name="joinType"></param>
/// <returns></returns>
/// <remarks>
/// <para>http://stackoverflow.com/questions/2379747/create-combined-datatable-from-two-datatables-joined-with-linq-c-sharp?rq=1</para>
/// <para>http://msdn.microsoft.com/en-us/library/vstudio/bb397895.aspx</para>
/// <para>http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html</para>
/// <para>http://stackoverflow.com/questions/406294/left-join-and-left-outer-join-in-sql-server</para>
/// </remarks>
public static DataTable JoinTwoDataTablesOnOneColumn(DataTable dtblLeft, DataTable dtblRight, string colToJoinOn, JoinType joinType)
{
//Change column name to a temp name so the LINQ for getting row data will work properly.
string strTempColName = colToJoinOn + "_2";
if (dtblRight.Columns.Contains(colToJoinOn))
dtblRight.Columns[colToJoinOn].ColumnName = strTempColName; //Get columns from dtblLeft
DataTable dtblResult = dtblLeft.Clone(); //Get columns from dtblRight
var dt2Columns = dtblRight.Columns.OfType<DataColumn>().Select(dc => new DataColumn(dc.ColumnName, dc.DataType, dc.Expression, dc.ColumnMapping));
//Get columns from dtblRight that are not in dtblLeft
var dt2FinalColumns = from dc in dt2Columns.AsEnumerable()
where !dtblResult.Columns.Contains(dc.ColumnName)
select dc; //Add the rest of the columns to dtblResult
dtblResult.Columns.AddRange(dt2FinalColumns.ToArray()); //No reason to continue if the colToJoinOn does not exist in both DataTables.
if (!dtblLeft.Columns.Contains(colToJoinOn) || (!dtblRight.Columns.Contains(colToJoinOn) && !dtblRight.Columns.Contains(strTempColName)))
{
if (!dtblResult.Columns.Contains(colToJoinOn))
dtblResult.Columns.Add(colToJoinOn);
return dtblResult;
} switch (joinType)
{ default:
case JoinType.Inner:
#region Inner
//get row data
//To use the DataTable.AsEnumerable() extension method you need to add a reference to the System.Data.DataSetExtension assembly in your project.
var rowDataLeftInner = from rowLeft in dtblLeft.AsEnumerable()
join rowRight in dtblRight.AsEnumerable() on rowLeft[colToJoinOn] equals rowRight[strTempColName]
select rowLeft.ItemArray.Concat(rowRight.ItemArray).ToArray(); //Add row data to dtblResult
foreach (object[] values in rowDataLeftInner)
dtblResult.Rows.Add(values);
#endregion
break;
case JoinType.Left:
#region Left
var rowDataLeftOuter = from rowLeft in dtblLeft.AsEnumerable()
join rowRight in dtblRight.AsEnumerable() on rowLeft[colToJoinOn] equals rowRight[strTempColName] into gj
from subRight in gj.DefaultIfEmpty()
select rowLeft.ItemArray.Concat((subRight== null) ? (dtblRight.NewRow().ItemArray) :subRight.ItemArray).ToArray();
//Add row data to dtblResult
foreach (object[] values in rowDataLeftOuter)
dtblResult.Rows.Add(values);
#endregion
break;
}
//Change column name back to original
dtblRight.Columns[strTempColName].ColumnName = colToJoinOn;
//Remove extra column from result
dtblResult.Columns.Remove(strTempColName);
return dtblResult;
}
}
Join two DataTables in C#的更多相关文章
- datatables增删改查的实现
学习可参考:http://www.guoxk.com/node/jquery-datatables http://yuemeiqing2008-163-com.iteye.com/blog/20069 ...
- JQuery Datatables服务器端处理示例
HTML <table class="table table-striped table-bordered table-hover" id="table_repor ...
- jquery dataTables.min.js API
demo: http://datatables.net/release-datatables/examples/api/select_single_row.html 选择一行http://datata ...
- Jquery Datatables 请求参数及接收参数处理
Jquery Datatables 请求参数及接收参数处理 /** * Created by wb-wuyifu on 2016/8/9. */ /** * Created by wb-wuyifu ...
- JQuery插件datatables相关api
学习可参考:http://www.guoxk.com/node/jquery-datatables http://yuemeiqing2008-163-com.iteye.com/blog/20069 ...
- jquery datatables api (转)
学习可参考:http://www.guoxk.com/node/jquery-datatables http://yuemeiqing2008-163-com.iteye.com/blog/20069 ...
- 最全的jquery datatables api 使用详解
学习可参考:http://www.guoxk.com/node/jquery-datatables http://yuemeiqing2008-163-com.iteye.com/blog/20069 ...
- jquery datatables api
原文地址 学习可参考:http://www.guoxk.com/node/jquery-datatables http://yuemeiqing2008-163-com.iteye.com/blog/ ...
- SQL Server-聚焦IN VS EXISTS VS JOIN性能分析(十九)
前言 本节我们开始讲讲这一系列性能比较的终极篇IN VS EXISTS VS JOIN的性能分析,前面系列有人一直在说场景不够,这里我们结合查询索引列.非索引列.查询小表.查询大表来综合分析,简短的内 ...
随机推荐
- 实验一、熟悉DOS命令
实验一.熟悉DOS命令 实验一.熟悉DOS命令 一. 实验目的 1.从操作系统理论的观点来了解和掌握DOS有关用户接口的特点: 2.熟悉常用DOS操作命令(md.cd.rd.copy.m ...
- SqlServer性能优化 即席查询(十三)
执行计划,查询类别: 1.即席查询 2.预定义查询 select c.EnglishProductCategoryName,p.EnglishProductName,p.Color,p.Siz ...
- php语言的几种循环语句的使用格式,及其区别
while 只要指定的条件成立,则循环执行代码块 do...while 首先执行一次代码块,然后在指定的条件成立时重复这个循环 for 循环执行代码块指定的次数 foreach 根据数组中每个元素来循 ...
- IOS开发官方文档随笔
马上着手开发IOS应用程序 创建第一个单视图应用 ###main 方法 int main(int argc, char * argv[]) { @autoreleasepool { return UI ...
- Add and Search Word
Trie 树的一个应用 Design a data structure that supports the following two operations: void addWord(word) b ...
- RNN 入门学习资料整理
建议按序阅读 1. RNN的一些简单概念介绍 A guide to recurrent neural networks and backpropagation Deep learning:四十九(RN ...
- [c++] vector的使用
} { vec.push_back(value); } { vector< vector<,); vector<, sec ...
- nodeType、nodeName和nodeValue
首先了解一下DOM中有三大节点,分别是 元素节点,文本节点,属性节点 元素节点:构成了DOM的基础.文档结构中,<html>是根元素,代表整个文档,其他的还有<head>,&l ...
- pyqt4:线程的串联运行方式
有些时候我们在pyqt中需要线程串行运行,而不是并发运行,用以下方式,这是在网上找的,暂存. > Hello > I have something like the foll scenar ...
- (转)Should 断言的基本使用方法
一.基础 RobotFramework带有丰富的系统关键,使用时无需导入,直接使用,为写自动化用例带来了极大的方便:不能停留在知道或者是会得程度,只有熟练使用各关键字,才能提升自动化用例的写作效率.下 ...