Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SqlReader issue

I'am posting on this forum for the first time . and I really hope I can find some help . What I'am doing is load about ... 1000 Value (example) from SQL and I'am doing it just fine .

the query for example is : Select Value from DatabaseA.dbo.Values

that "Value" ==> decimal(10, 2)

sqlConnection2.Open();
insertCommand2.ExecuteNonQuery();
SqlDataReader reader2 = insertCommand2.ExecuteReader();
if (reader2.HasRows)
{
  while (reader2.Read())
  {
    decimal Value = reader.GetDecimal(0);

this propably should work fine . but What I want to do is to make + on all of them ... For example first value = 16 , second = 28 , third : 78

I want to make 16 + 28 + 78 ... but for all Values that Loaded them . How Can I do that please ? , thanks .

like image 492
Stack overflow Avatar asked Mar 28 '26 22:03

Stack overflow


1 Answers

Assuming you want to keep the original values as well, you could have a List<decimal> and accumulate the totals.

List<decimal> totals = new List<decimal>();

Then in your while loop:

totals.Add(Value);

You can then return the running total via:

var runningTotal = totals.Sum();

If you do not want the original values, you can just use:

 decimal value;
 while (reader2.Read())
 {
    value += reader.GetDecimal(0);
 }
like image 52
Darren Avatar answered Mar 31 '26 11:03

Darren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!