如何在c#中左外连接两个数据表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17684448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Left Outer Join two DataTables in c#?
提问by Soenhay
How can I Left Outer Join (I think it is Left Outer Join but I am not 100% sure) two data tables with the following tables and conditions while keeping all columns from both tables?
我怎样才能左外连接(我认为它是左外连接,但我不是 100% 确定)具有以下表格和条件的两个数据表,同时保留两个表中的所有列?
dtblLeft:
dtbl左:
id col1 anotherColumn2
1 1 any2
2 1 any2
3 2 any2
4 3 any2
5 3 any2
6 3 any2
7 any2
dtblRight:
右:
col1 col2 anotherColumn1
1 Hi any1
2 Bye any1
3 Later any1
4 Never any1
dtblJoined:
dtbl加入:
id col1 col2 anotherColumn1 anotherColumn2
1 1 Hi any1 any2
2 1 Hi any1 any2
3 2 Bye any1 any2
4 3 Later any1 any2
5 3 Later any1 any2
6 3 Later any1 any2
7 any2
Conditions:
状况:
- In dtblLeft, col1 is not required to have unique values.
- In dtblRight, col1 has unique values.
- If dtblLeft is missing a foreign key in col1 or it has one that does not exist in dtblRight then empty or null fields will be inserted.
- Joining on col1.
- 在 dtblLeft 中,col1 不需要具有唯一值。
- 在 dtblRight 中,col1 具有唯一值。
- 如果 dtblLeft 在 col1 中缺少外键,或者它有一个在 dtblRight 中不存在的外键,则将插入空或空字段。
- 在 col1 上加入。
I can use regular DataTable operations, LINQ, or whatever.
我可以使用常规的 DataTable 操作、LINQ 或其他任何操作。
I tried this but it removes duplicates:
我试过这个,但它删除了重复项:
dtblA.PrimaryKey = new DataColumn[] {dtblA.Columns["col1"]}
DataTable dtblJoined = new DataTable();
dtblJoined.Merge(dtblA, false, MissingSchemaAction.AddWithKey);
dtblJoined.Merge(dtblB, false, MissingSchemaAction.AddWithKey);
EDIT 1:
编辑 1:
This is close to I what I want but it only has columns from one of the tables ( found at this link):
这与我想要的很接近,但它只有其中一个表中的列(可在此链接中找到):
dtblJoined = (from t1 in dtblA.Rows.Cast<DataRow>()
join t2 in dtblB.Rows.Cast<DataRow>() on t1["col1"] equals t2["col1"]
select t1).CopyToDataTable();
EDIT 2:
编辑2:
An answer from this linkseems to work for me but I had to change it a bit as follows:
此链接的答案似乎对我有用,但我不得不对其进行如下更改:
DataTable targetTable = dtblA.Clone();
var dt2Columns = dtblB.Columns.OfType<DataColumn>().Select(dc =>
new DataColumn(dc.ColumnName, dc.DataType, dc.Expression, dc.ColumnMapping));
var dt2FinalColumns = from dc in dt2Columns.AsEnumerable()
where targetTable.Columns.Contains(dc.ColumnName) == false
select dc;
targetTable.Columns.AddRange(dt2FinalColumns.ToArray());
var rowData = from row1 in dtblA.AsEnumerable()
join row2 in dtblB.AsEnumerable()
on row1["col1"] equals row2["col1"]
select row1.ItemArray.Concat(row2.ItemArray.Where(r2 => row1.ItemArray.Contains(r2) == false)).ToArray();
foreach (object[] values in rowData)
targetTable.Rows.Add(values);
I also found this linkand I might try that out since it seems more concise.
我也找到了这个链接,我可能会尝试一下,因为它看起来更简洁。
EDIT 3 (11/18/2013):
编辑 3 (11/18/2013):
Updated tables to reflect more situations.
更新了表格以反映更多情况。
采纳答案by Soenhay
Thanks all for your help. Here is what I came up with based on multiple resources:
感谢你的帮助。这是我根据多种资源得出的结论:
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 = 0,
/// <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 = 1
}
/// <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;
}
}
EDIT 3:
编辑 3:
This method now works correctly and it is still fast when the tables have 2000+ rows. Any recommendations/suggestions/improvements would be appreciated.
此方法现在可以正常工作,并且当表有 2000 多行时它仍然很快。任何建议/建议/改进将不胜感激。
EDIT 4:
编辑 4:
I had a certain scenario that led me to realize the previous version was really doing an inner join. The function has been modified to fix that problem. I used info at this linkto figure it out.
我有一个特定的场景,让我意识到以前的版本确实在进行内部联接。该功能已被修改以解决该问题。我使用此链接中的信息来弄清楚。
回答by triad_Mike
You could probably use LINQ and do something like this:
您可能可以使用 LINQ 并执行以下操作:
var dtblJoined = from dB in dtblB.AsEnumerable()
join dA in dtblA.AsEnumerable() on dA.col1 equals dB.col1 into dAB
from d in dAB.DefaultIfEmpty()
select new (col1 = dB.col1, ; col2 = (dB.col1 == dA.col1) ? dA.col2 : null);
This would return an IEnumerable as the result not a DataTable, but it should get you closer to what you are looking for I think. May need a little tweaking though.
这将返回一个 IEnumerable 作为结果而不是数据表,但它应该让你更接近你正在寻找的我认为。不过可能需要稍微调整一下。
回答by Icarus
This is simply an inner join between the 2 tables:
这只是两个表之间的内部连接:
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();
Produces:
产生:
col1 col2
1 Hi
1 Hi
2 Bye
3 Later
3 Later
3 Later