2017-10-18 128 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];