简体   繁体   中英

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.
  2. else add row.

Example: Instead of multiple records for same Department and DocumentID

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.

Any tips?

You can search your datatable with the Select method which use a SQL like syntax for the filtering.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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