问题
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