2017-10-18 127 views
0

我使用沒有MVC的剃鬚刀C#。我正在使用來自SQL的數據進行即時計算。我想要做的就是將結果存儲到一個數組中,以便以後總和。將計算結果存儲到數組中C#

conn.SQL = .... 

     //set up connection 
     SqlConnection connect = new SqlConnection(...); 
     connect.Open(); 

     //create the data reader 
     SqlCommand cmd = new SqlCommand(....., connect); 
     SqlDataReader dr = cmd.ExecuteReader(); 
     cmd.Dispose(); 


     while (dr.Read()) 
     { 


      foo = 0 
      bar = 0; 

      //get local variables from database 

      foo = Math.Round(Convert.ToDouble(dr["foo"]), 2); 

      bar = Math.Round(Convert.ToDouble(dr["bar"]), 2); 

      foo = var - foo2 - foo3; 
try 
      { 
       if ((foo/var) >= .5) 
       { 
        if (foo <= 0.00) 
        { 
         bar = 0.00; 
         bar = var * .5; 
        } 

        else 
        { 
         MyVar = bar * .7 - foo;//This is the calculation done on the fly. 
         foo = bar * .5; 
         // MyVar_array = [];// This is the array I want to store the results to summed later on 
        } 

       } 

      } 
      catch (Exception e) 
      { 

      } 

這些都是計算,然後我在一個表

的數據顯示正確顯示這些@ foo.ToString(「C」)和計算是正確的>問題是我想從這一欄中獲得總數。當試圖給我們一個數組時,我從當前上下文中不存在各種錯誤。之後,我會在我的代碼頂部聲明,然後我會收到一個錯誤,說我可以在這個範圍內使用這個變量。

+1

你的問題是各項指標? –

+0

我的朋友,你還沒有問過一個問題。什麼給你帶來困難?你不知道如何聲明數組?如何更新它?如何顯示其內容?您的示例不包含任何循環,SQL或HTML,因此我不知道您在哪裏遇到問題,或者示例中的代碼如何應用於此問題。 –

回答

0

不知道你在做什麼,但這是你如何將一些東西存儲在數組中。

decimal[] MyVar_array = new decimal[1]; 
MyVar_array[0] = new decimal(0.123); 
//access the first item in the array like this 
Debug.Print(MyVar_array[0].ToString()); 

我真的覺得你想看看使用類雖然。要管理該項[0]與您設置的任何變量相對應會更難。再加上一個數組,你現在需要創建它有多大。處理對象要容易得多。這樣

public class MyStuff 
{ 
    public decimal MyVar 
    { 
     get;set; 
    } 
} 

使用的東西像這樣

static void Main(string[] args) 
    { 
     MyStuff myData = new MyStuff(); 
     myData.MyVar = new decimal(0.123); 
     Debug.Print(myData.MyVar.ToString()); 
     Debug.Print(""); 
    } 

它的使用對象更容易管理和組織您的數據。

+0

我試圖在列中添加數據。我試圖存儲的數字是從MS SQL數據中提取的計算結果。由於我在沒有MVC的情況下使用Razor,因此顯示器是HTML表格​​@ bar.ToString(「C」)。我有一個循環什麼循環,並給出了表的大小,但因爲計算是在飛行中完成的,我無法總結這些數字。 –

0

你可以用列表和它是非常容易

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

try 
{ 
    if ((foo/var) >= .5) 
    { 
     if (foo <= 0.00) 
     { 
      bar = 0.00; 
      bar = var * .5; 
     } 

     else 
     { 
      MyVar = bar * .7 - foo;//This is the calculation done on the fly. 
      foo = bar * .5; 
      // MyVar_array = [];// This is the array I want to store the results to summed later on 
     } 

    } 
    //x.Add(foo); im not sure which is you are storing 
    x.Add(bar); 

} 
catch (Exception e) 
{ 

} 

,那麼你可以調用數組類似

decimal firstvalue = x[0]; 
decimal secondvalue = x[1];