我将如何过滤该数据集?

时间:2019-02-27 18:08:03

标签: c# .net asp.net-core

我有一个看起来像图像的数据集。我正在尝试按表格进行过滤,并获取表格旁边的所有列,并将它们与其他数据集进行比较

此数据集包含名为表1和表2的表,并且当它们被选择时,它们如下图所示。它显示了列,我需要将这些列与第一个数据集

中的匹配表中的行进行比较

我已经看过dataview了,但这将需要很多工作,而且我经验不足。我正在尝试找到一种实现foreach循环的方法,该循环将获取第一个数据集中的表名,然后将其中的行与第二个数据集中与表名匹配的第二个数据集中的数据表中的列进行比较。第一个数据集。

1 个答案:

答案 0 :(得分:0)

在不了解这些DataSets的更多信息(例如它们是否具有主键,列的数据类型,每个表中的行数等)的情况下,我只能提供有限的帮助。下面的示例尝试尽可能通用,避免一些基本问题:

DataSet ds1 = <<fetch dataset1>>;
DataSet ds2 = <<fetch dataset2>>;
foreach (DataTable tbl1 in ds1.Tables)
{
    if (ds2.Tables.Contains(tbl1.TableName))
    {
        DataTable tbl2 = ds2.Tables[tbl1.TableName];
        List<string> commonColumnNames = new List<string>(tbl1.Columns.Cast<DataColumn>().Select(c => c.ColumnName).Intersect(tbl2.Columns.Cast<DataColumn>().Select(c => c.ColumnName)));
        int maxRows = Math.Min(tbl1.Rows.Count, tbl2.Rows.Count);
        for (int r = 0; r <= maxRows; r++)
        {
            foreach (string colName in commonColumnNames)
            {
               if (tbl1.Rows[r][colName] != tbl2.Rows[r][colName])
               {
                    // Different value
               }
            }
        }
    }
}

更新1:我在以下示例中添加了注释,以逐步说明此代码的作用。就像我之前说过的那样,由于我对您的数据不太了解,因此我不得不添加额外的代码。此额外的代码用于处理以下内容:“两个数据集中是否存在表ABC?”,“两个表中是否具有相同的列?”,“表中的行数是否相同?” ?”。您最初的问题没有此信息,所以我使此代码更健壮,可以处理这些未知数。

DataSet ds1 = <<fetch dataset1>>;
DataSet ds2 = <<fetch dataset2>>;

// Loop through all of the tables in the 1st DataSet
foreach (DataTable tbl1 in ds1.Tables)
{
    // If the 2nd DataSet has a table with same name as the one from the 1st DataSet
    if (ds2.Tables.Contains(tbl1.TableName))
    {
        DataTable tbl2 = ds2.Tables[tbl1.TableName];
        // Create a list of column names that the two tables have in common.
        // We will only compare the values in these two tables, in this set of matching column names.

        List<string> commonColumnNames = new List<string>(tbl1.Columns.Cast<DataColumn>().Select(c => c.ColumnName).Intersect(tbl2.Columns.Cast<DataColumn>().Select(c => c.ColumnName)));
        // Before we start comparing the rows in the two tables, find out which one has the fewer number of rows in it.
        int maxRows = Math.Min(tbl1.Rows.Count, tbl2.Rows.Count);
        // If the tables have a different number of rows, then we will only compare the set of rows numbered 0-to-MinRowCount
        for (int r = 0; r <= maxRows; r++)
        {
            // For each row, compare the values of common columns
            foreach (string colName in commonColumnNames)
            {
               if (tbl1.Rows[r][colName] != tbl2.Rows[r][colName])
               {
                    // Different value
               }
            }
        }
    }
}
相关问题