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的性能分析,前面系列有人一直在说场景不够,这里我们结合查询索引列.非索引列.查询小表.查询大表来综合分析,简短的内 ...
随机推荐
- 关于JAVA的数据转换总结
数据转换在编程里面是十分常用的,将平常可能用到的数据转换类型总结起来会在以后码代码的过程中有很大帮助. 在数据转换之前,需要明白的是基础数据类型的自动转换和强制转换.接下来就先从数据类型的容量讲起. ...
- Protobuf - 使用scons编译proto文件
使用protobuf过程中,需要先对消息结构进行定义,文件以.proto格式结尾.然后要使用google提供的protoc命令行,把.proto文件转成对应的代码文件. protoc --proto_ ...
- Java(五)
♥作业1: 显示指定路径所有文件及实现文件筛选.智能监控,程序能自动在下拉菜单生成任意路径下文件所有尾缀. 代码内注释内容为步骤与整体思路 import java.awt.BorderLayout ...
- POJ 2976
http://poj.org/problem?id=2976 01分数规划问题,可以舍掉k组 01分数规划用于解决的经典问题是最优比率生成树 解法见http://www.cnblogs.com/lot ...
- Network Assistant (Alpha)版使用说明
Network Assistant (网络助手)使用说明 本软件是一款帮助同学方便Ip更改,小蝴蝶断线重连,一键wifi,定时关机的软件.它集成 ...
- IC卡复位应答ATR的数据元和它们的意义
ISO/IEC 7816-3标准中对ATR的数据串和数据元做了规定和描述.ATR的数据元和它们的意义: 数据元 说明 TS 起始字符 T0 格式字符 TA1,TB1,TC1,TD1,... 接口字符 ...
- redis-cluster 单个节点不可用
背景: 公司的音视频 盗版检测业务,使用redis-cluster作为 key-value 数据库, 使用张图片的 特征hash值作key.因为数据量太大,机器有限,集群内没有slaver 问题描述 ...
- Java设计模式(一) 简单工厂模式不简单
摘要:本文介绍了简单工厂模式的概念,优缺点,实现方式,以及结合Annotation和反射的改良方案(让简单工厂模式不简单).同时介绍了简单工厂模式(未)遵循的OOP原则.最后给出了简单工厂模式在JDB ...
- 实现TCP、UDP相互通信及应用
实验名称 Socket编程综合实验(1) 一.实验目的: 1.理解进程通信的原理及通信过程 2.掌握基于TCP和UDP的工作原理 3.掌握基本的Socket网络编程原理及方法 二.实验内容 1.掌握 ...
- sql指定插入自增长id的数据
SET IDENTITY_Insert [Tag.V2].[dbo].[Members_EnAccount] ON; insert into [Tag.V2].[dbo].[Members_EnAcc ...