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的性能分析,前面系列有人一直在说场景不够,这里我们结合查询索引列.非索引列.查询小表.查询大表来综合分析,简短的内 ...
随机推荐
- Direct3D 10学习笔记(二)——计时器
本篇将简单整理Direct3D 10的计时器实现,具体内容参照< Introduction to 3D Game Programming with DirectX 10>(中文版有汤毅翻译 ...
- JAVA(3)
接口注意事项: 1.接口不能被实例化 2.接口中所有的方法都不能有主体 (不能有{ }) 3.一个类可以实现多个接口 4.接口中可以有变量<但变量不能用private和protected修饰& ...
- S2SH+mysql-软件开发实际部署问题-8个小时后提示MYSQL数据库无法连接
type Exception report message description The server encountered an internal error () that prevented ...
- maven打包不执行测试用例
在执行maven打包时不需要执行测试用例,使用如下2种方式实现:-DskipTests=true : 不执行测试用例,但编译测试用例类生成相应的class文件至target/test-classes下 ...
- 解决Cannot delete or update a parent row: a foreign key constraint fails (`current_source_products`.`product_storage`, CONSTRAINT `product_storage_ibfk_3` FOREIGN KEY (`InOperatorID`)
出现这个异常的原因是因为设置了外键,造成无法更新或删除数据. 1.通过设置FOREIGN_KEY_CHECKS变量来避免这种情况 删除前设置 SET FOREIGN_KEY_CHECKS=0; 删除完 ...
- JAVA,NET RSA密钥格式转换
JAVA和NET RSA密钥格式相互转换(公钥,私钥) 做了一个小项目遇到java和.net非对称加密问题,java的公钥和私钥就直接是一个字符串的形式展示的,但是.net是以xml简单包裹形式展示的 ...
- 第五章 搭建S3C6410开发板测试环境
开发板是开发和学习嵌入式技术的主要设备.在这章中介绍了S3C6410开发板,它是三星公司推出的一款低功耗.高性价比的RISC处理器.安装串口调试工具:minicom.它的安装步骤:第1步:检测当前系统 ...
- linux apache 配置URL地址栏大小写不敏感配置
1.apache配置 解决如下:把mod_speling.so放到apache目录下的 lib中... 然后修改http.conf文件, 加入:LoadModule speling_module /u ...
- Eclipse动态web工程(Dynamic Web Project)添加jar文件的正确方法
Eclipse中,创建了动态web工程之后,如果需要添加新的jar文件,有两种方法.第一种是配置工程的“build path”,第二种则是将jar文件放在工程目录下的“/WebContent/WEB- ...
- cocos2d-x 帧循环不严谨造成场景切换卡顿
最近在用cocos2d-x做引导界面,2dx版本是2.2.3,场景切换加上了效果,所有资源都已经使用texturepacker打包预加载,但是在实际运行调试中,场景切换相当卡顿. 各种纠结后,无意中将 ...