合并两个DataTable,而不包含列的重复值 [英] Merge two DataTables without duplicate values for a column
本文介绍了合并两个DataTable,而不包含列的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个DataTable,比如
DataTable1 -
IDPart1 | IDPart2   次> | 类型次> |
---|---|---|
1 | A | 类型1 | 1 | A | Type2 |
DataTable2 -
IDPart1 | IDPart2   次> | 范围次> |
---|---|---|
1 | A | 100 | 1 | A | 200 |
1 | A | < td> 300
现在我需要我的主数据表: -
IDPart1 | IDPart2 &NBSP; 次> | 范围&NBSP; &NBSP; 次> | 类型次> |
---|---|---|---|
1 | A | 100 | 类型1 |
1 | A | 200 | 2型 |
A | 300 |
这里IDPart1和IDPart2是两个数据表的公共列。现在对于ID 1-A,我在DataTable1中有2条记录,在DataTable2中有3条记录。
我希望我的DataTable有3条记录,其中DataTable1的类型列由于记录较少而有一个空字符串DataTable1。
注意:可能有一种情况,我在DataTable2中记录较少,而DataTable1中有更多记录用于ID组合。
LINQ中是否有任何方法可以实现此目的。
I have two DataTables like
DataTable1-
IDPart1 | IDPart2 | Type |
---|---|---|
1 | A | Type1 |
1 | A | Type2 |
DataTable2-
IDPart1 | IDPart2 | Range |
---|---|---|
1 | A | 100 |
1 | A | 200 |
1 | A | 300 |
Now I need my main datatable to be :-
IDPart1 | IDPart2 | Range | Type |
---|---|---|---|
1 | A | 100 | Type1 |
1 | A | 200 | Type2 |
1 | A | 300 |
Here IDPart1 and IDPart2 are common columns for both datatable. Now for ID 1-A, i have 2 records in DataTable1 and 3 records in DataTable2.
I want my DataTable to have 3 records with type column from DataTable1 to have an empty string due to lesser records in DataTable1.
Note: There might be a case when I have lesser records in DataTable2 and more records in DataTable1 for a ID combination.
Is there any way in LINQ or any other way to achieve this.
推荐答案
请试试这个。
Hi,
Please try this.
List<table1> lstt1 = new List<table1>();
lstt1.Add(new Table1() { IDPart1 = "1A", Type = "T1" });
lstt1.Add(new Table1() { IDPart1 = "1A", Type = "T2" });
List<table2> lstt2 = new List<table2>();
lstt2.Add(new Table2() { IDPart1 = "1A", Range = 100 });
lstt2.Add(new Table2() { IDPart1 = "1A", Range = 200 });
lstt2.Add(new Table2() { IDPart1 = "1A", Range = 300 });
var items = from itm1 in lstt1
join itm2 in lstt2 on itm1.IDPart1 equals itm2.IDPart1
into grouping
from itm2 in grouping.DefaultIfEmpty(new Table2())
select new { itm1.IDPart1, itm1.Type, itm2.Range };
这篇关于合并两个DataTable,而不包含列的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文