Compare two datarows

2019-05-06 18:08发布

I have a datatable with multiple rows inside it. I have got 1 more row and I want to check if this row is a duplicate of the existing rows in the datatable. So I tried like:

DataTable dataTable = GetTable();
if (dataTable.Rows.Count > 1)
{
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        var dataRow = dataTable.Rows[i];

        if (dt.Rows.Contains(dataRow) && dt.Rows.Count != 0)  // Giving error
            continue;
        dt.ImportRow(dataRow);
        return dataRow;
    }
}

Here, my dataTable can also be null/empty for the first time.

But its giving error as:

Table doesn't have a primary key.

Can anyone help me please. If additional code is required, just comment.

2条回答
叼着烟拽天下
2楼-- · 2019-05-06 18:17

Can't you add the PK on your DataTable object?

I think the code would be something like this:

dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["Id"] };
查看更多
Deceive 欺骗
3楼-- · 2019-05-06 18:26
DataTable dataTable = GetTable();
if (dataTable.Rows.Count > 1)
{
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        var dataRow = dataTable.Rows[i];

        if (dt.Rows.Contains(dataRow) && dt.Rows.Count != 0)  // Giving error
            continue;
        dt.ImportRow(dataRow);
        return dataRow;
    }
}

I assume that your dt variable is supposed to be your dataTable variable, if you are getting an error telling you that your table doesn't have a primary key it could be because you are using the wrong variable and that there really isn't a primary key or a table associated with the variable that you are trying to use.

so I assume that the code should look like this instead

DataTable dataTable = GetTable();
if (dataTable.Rows.Count > 1)
{
    for (int i = 0; i < dataTable.Rows.Count; i++)
    {
        var dataRow = dataTable.Rows[i];

        if (dataTable.Rows.Contains(dataRow) && dataTable.Rows.Count != 0)  // Giving error
            continue;
        dataTable.ImportRow(dataRow);
        return dataRow;
    }
}
查看更多
登录 后发表回答