2015-03-19 13 views
0

我有两个数据表Datatable1和Datatable2。 Datatable1是另一个的子集。我想知道哪些行是新的,哪些是匹配的,哪些是不匹配的。想要在Datatable1中添加新行,并添加值 - 新建,匹配和不匹配。请建议一个优化的方式来做到这一点。在C#中比较两个数据表并查找新的,匹配和非管理记录

例如: Datatable1:

DataTable table = new DataTable(); 
table.Columns.Add("ID", typeof(int)); 
table.Columns.Add("Name1", typeof(string)); 
table.Columns.Add("Name2", typeof(string)); 
//New 
table.Rows.Add(25, "Ciya", "David"); 
table.Rows.Add(51, "Kiya", "Cecil"); 
//Matching 
table.Rows.Add(50, "Bina", "Cecil"); 
//Non matching 
table.Rows.Add(21, "Riya", "Janet"); 
table.Rows.Add(10, "Rita", "Christoff"); 

Datatable2:

DataTable table = new DataTable(); 
table.Columns.Add("ID", typeof(int)); 
table.Columns.Add("Name1", typeof(string)); 
table.Columns.Add("Name2", typeof(string)); 

table.Rows.Add(10, "Lisa", "Christoff"); 
table.Rows.Add(21, "Combivent", "Janet"); 
table.Rows.Add(50, "Bina", "Cecil"); 
+1

看一看的[ “相关”(http://stackoverflow.com/questions/164144/compare-two-datatables-to-determine-rows-in-one-but-not-the - 其他)本页右侧的问题列表。你会发现不同的答案,为你提供尝试(同时学习)的机会。 一旦你尝试了,并有一个更具体的问题,然后回来问,如果你自己找不到任何答案。 – 2015-03-19 06:35:13

回答

1

您可以使用LINQ的方法,其可用于可枚举类型,如IntersectExcept尝试。这是做这个的一个例子。

// Get matching rows from the two tables 
IEnumerable<DataRow> matchingRows = table1.AsEnumerable().Intersect(table2.AsEnumerable()); 

// Get rows those are present in table2 but not in table1 
IEnumerable<DataRow> rowsNotInTableA = table2.AsEnumerable().Except(table1.AsEnumerable()); 
+0

这将参考比较行而不是他们的内容。 – Magnus 2015-03-19 08:24:48

+0

嗨,感谢您的答案,但是当我使用Intersect时,IEnumerable返回空。 – Learner 2015-03-19 09:04:44

相关问题