检查要在 C# 中更新或插入的数据表的值

Check value of datatable to update or insert in c#

我有一个具有以下结构的数据table:

Department | DocumentID | Days

在向该数据添加行之前table我应该考虑两种情况:

  1. 如果 DepartmentDocumentID 已经存在,更新同一行中的天数。
  2. 否则添加行。

示例: 而不是相同 DepartmentDocumentID

的多个记录
Marketing       | 1 | 10
Human Resources | 1 | 5
Marketing       | 1 | 5
Marketing       | 2 | 5

应将天数添加到现有行

Marketing       | 1 | 15
Human Resources | 1 | 5
Marketing       | 2 | 5

如果这不容易做到,我想将多个记录添加到一个 table,然后对 DepartmentDocumentID 相同的天数求和,但我没有也成功做到这一点。

有什么建议吗?

您可以使用 Select 方法搜索您的数据表,该方法使用类似 SQL 的过滤语法。

然后插入新行或更新您找到的行。

var rows = dataTable.Select(string.Format("DocumentId = {0}", documentId));

if (rows.Length == 0)
{
   // Add your Row
}
else
{
   // Update your Days
   rows[0]["Days"] = newDayValue;
}