Reputation: 1973
I have a datatable with following structure:
Department | DocumentID | Days
Before I add rows to this datatable I should consider two situations:
Department
and DocumentID
already exists, update number of Days in same 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
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