将计算结果存储到数组C#中

时间:2017-10-18 01:31:02

标签: c# arrays razor

我正在使用没有MVC的剃刀C#。我正在使用SQL中的数据来动态进行计算。我想要做的是将结果存储到一个数组中,以便我可以稍后对总数求和。

 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(&#34; C&#34)

数据正确显示且计算正确&gt;问题是我试图从这个专栏中得到一个总数。当我们尝试使用数组时,从中获取各种错误并不存在于当前上下文中。之后我将在我的代码顶部声明,然后我将收到一个错误,说我可以在此范围内使用此变量。

2 个答案:

答案 0 :(得分:0)

不确定您要做什么,但这是您在数组中存储内容的方式。

"

我真的认为你想要考虑使用类。管理该项[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());

像这样使用

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

使用对象管理和整理数据更加容易。

答案 1 :(得分:0)

你可以使用List,它更容易

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];
相关问题