简体   繁体   English

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

[英]Check value of datatable to update or insert in c#

I have a datatable with following structure: 我有一个具有以下结构的数据表:

Department | DocumentID | Days

Before I add rows to this datatable I should consider two situations: 在我向此数据表添加行之前,我应该考虑两种情况:

  1. If Department and DocumentID already exists, update number of Days in same row. 如果DepartmentDocumentID已存在,请更新同一行中的天数。
  2. else add row. 否则添加行。

Example: Instead of multiple records for same Department and DocumentID 示例:代替同一DepartmentDocumentID的多个记录

Marketing       | 1 | 10
Human Resources | 1 | 5
Marketing       | 1 | 5
Marketing       | 2 | 5

Should add number of days to existing row 应该在现有行中添加天数

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

If this is not easily doable, I thought of adding multiple records to one table and then sum days where Department and DocumentID are the same, but I didn't succeed in doing this also. 如果这不容易做到,我想到将多个记录添加到一个表中,然后将DepartmentDocumentID相同的天数相加,但我也没有成功。

Any tips? 有小费吗?

You can search your datatable with the Select method which use a SQL like syntax for the filtering. 您可以使用Select方法搜索数据表,该方法使用类似SQL的语法进行过滤。

Then either insert a new row or update the one you found. 然后插入新行或更新找到的行。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM