Compare two datarows

风格不统一 提交于 2019-12-07 11:37:33

问题


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.


回答1:


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"] };



回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/8993499/compare-two-datarows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!