iamdlm
iamdlm

Reputation: 1973

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?

Upvotes: 1

Views: 1882

Answers (1)

Juan
Juan

Reputation: 3705

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

Upvotes: 3

Related Questions