Skip to content
Advertisement

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 .

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement