【问题标题】:Comparing two datatables in C# and finding new, matching and non-macting records比较 C# 中的两个数据表并查找新的、匹配的和非匹配的记录
【发布时间】:2015-03-19 06:16:22
【问题描述】:

我有两个数据表,Datatable1 和 Datatable2。 Datatable1 是另一个的子集。我想找出哪些行是新的,哪些是匹配的,哪些是不匹配的。想要在 Datatable1 中添加一个新行,其中包含值 - 新的、匹配的和不匹配的。请提出一个优化的方法来做到这一点。

例如: 数据表1:

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");

数据表2:

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");

【问题讨论】:

  • 查看本页右侧的"Related" 问题列表。您会发现可能会为您提供尝试(并同时学习)的机会的不同答案。一旦您尝试过并遇到更具体的问题,如果您自己找不到任何答案,请回来询问。

标签: c# datatable


【解决方案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()); 

【讨论】:

  • 这将引用比较行而不是它们的内容。
  • 您好,感谢您的回答,但是当我使用 Intersect 时,IEnumerable 返回为空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 2013-04-02
  • 2020-10-04
相关资源
最近更新 更多