c# - 比较数据集或更好的想法

标签 c# linq ado.net .net-2.0 dataset

如何比较一个数据集与另一个数据集的值。

第一个数据集 [“正确的记录”] 来自具有列名称的 SQL Server

 [id], [subsNumber]

第二个数据集 [“正确和不正确的记录”] 来自进度数据库,除 1 列外,其他列均不同,即 subsNumber

如何制作另一个数据集,其中包含[“正确记录”]中的所有[subsNumber]以及第二个数据集[“正确不正确记录”]中的匹配记录?

删除第二个数据集中[“正确和不正确的记录”]中与第一个数据集中的“subsNumber”列不匹配的所有记录

或者任何其他想法

基本上,如何从与第一个数据集具有相同“subsNumber”的第二个数据集中获取所有记录

最佳答案

关键是使用 System.Data.DataRelation 将 2 个数据表连接到一个或多个公共(public)列上。

以下是从 KC's See Sharp Blog 上的帖子中派生的一些代码

public DataTable GetImproperRecords(DataTable ProperRecords, DataTable ImproperRecords) {
  DataTable relatedTable = new DataTable("Difference");
  try {
     using (DataSet dataSet = new DataSet()) {
        dataSet.Tables.AddRange(new DataTable[] { ProperRecords.Copy(), ImproperRecords.Copy() });

        DataColumn properColumn = new DataColumn();
        properColumn = dataSet.Tables[0].Columns[1]; // Assuming subsNumber is at index 1

        DataColumn improperColumn = new DataColumn();
        improperColumn = dataSet.Tables[1].Columns[0]; // Assuming subsNumber is at index 0

        //Create DataRelation
        DataRelation relation = new DataRelation(string.Empty, properColumn, improperColumn, false);

        dataSet.Relations.Add(relation);

        //Create columns for return relatedTable
        for (int i = 0; i < ImproperRecords.Columns.Count; i++) {
           relatedTable.Columns.Add(ImproperRecords.Columns[i].ColumnName, ImproperRecords.Columns[i].DataType);
        }

        relatedTable.BeginLoadData();

        foreach (DataRow parentrow in dataSet.Tables[1].Rows) {
           DataRow[] childrows = parentrow.GetChildRows(relation);

           if (childrows != null && childrows.Length > 0)
              relatedTable.LoadDataRow(parentrow.ItemArray, true);

        }

        relatedTable.EndLoadData();

     }
  }
  catch (Exception ex) {
     Console.WriteLine(ex.Message);
  }

  return relatedTable;
}

关于c# - 比较数据集或更好的想法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1014906/

相关文章:

.net - 事务中的 LAST_INSERT_ID() 是否可靠?

c# - 如何处理或检测 VB.NET 中的网络故障?

具有多个连接、计数和左连接的 SQL 到 LINQ

c# - 不要在成员签名中嵌套泛型类型

c# - 自定义 Linq 扩展的性能差异/改进

c# - 从字符串转换为uniqueidentifier时转换失败

c# - 统一设置发射颜色

c# - 冲浪/筛选/用于模板匹配

c# - 使用 div 显示错误

c# - 在 C# 中执行异步触发时省略 await 语句并忘记使用 ado.net 写入数据库是否安全