RRM
RRM

Reputation: 3451

sum of gridview column, skipping duplicates

I have a datagridview filled with data something like

Selected  ProductName InvoiceNr InvoiceValue
X         A           1         10
          B           1         10
X         C           2         20
          D           2         20
X         E           1         10
X         F           3         30
          G           4         40
X         H           2         20

I need to find a sum of chosen invoices but if any invoice was selected many times, it should go to the sum just once, so my sum would be 10+20+30.

I should be quite easy to count it in SQL but I need to do it in C#, probably in a loop going through all rows.

Any optimal way to do it?

I suppose datagridview is not important here, an algorithm with array would be useful for me too.

Upvotes: 0

Views: 122

Answers (1)

FabJC
FabJC

Reputation: 36

The simplest method is to use a List to keep track of the invoice numbers you've already added - in almost-pseudocode, something like this:

int sumOfValues = 0;
List<string> addedInvoiceNumbers = new List<string>();
foreach (DataRow dr in rows)
{
   //if row is selected and the list doesn't contain the InvoiceNumber
   if (dr[0] == true && !addedInvoiceNumbers.Contains(dr[2]))
   {
      sumOfValues += dr[3];
      addedInvoiceNumbers.Add(dr[2]);
   }
}

Hope this makes sense!

Upvotes: 1

Related Questions