C#如何比较范围两个数字的区别

时间:2015-10-02 04:49:01

标签: c# asp.net-mvc-4

我在C#MVC模型循环中比较范围两个数字时遇到了麻烦。内部循环示例SequenceId(int)编号1,2,4,6,7,9,12,16等...我需要找到Rage = next Number - previous Number。

这是我的C#方法。

if (model != null && ModelState.IsValid)
{
    foreach (var list in model)
    {
        int sIdRage = 1;
        int Interval =15;
        int previousNumber =1;
        //SequenceId will be 1,2,4,6,7,9,12,16 etc...
        // First Loop sIdRage = 1
        int sId = list.SequenceId;
        int nextNumber = (sId - previousNumber);
        //For the third loop nextNumber = 4 and previousNumbe = 2
        // sIdRage = nextNumber - previousNumbe
        // sIdRage = 2
        sIdRage += (sId - previousNumber);           
        count += TimeSpan.FromMinutes(Interval * sIdRage);
        list.FromTime = count.ToString();
        db.Entry(list).State = EntityState.Modified;
        db.SaveChanges();
    }
}

1 个答案:

答案 0 :(得分:1)

你的逻辑错误。您正在循环中不断初始化变量,因此它无法正常工作。另请参阅靠近底部的代码中的我的评论。它应该是这样的

if (model != null && ModelState.IsValid)
{
    int sIdRage = 1;
    int Interval =15;
    int previousNumber =1;
    //SequenceId will be 1,2,4,6,7,9,12,16 etc...
    // First Loop sIdRage = 1

    foreach (var list in model)
    {
        int sId = list.SequenceId;
        int nextNumber = (sId - previousNumber);
        //For the third loop nextNumber = 4 and previousNumbe = 2
        // sIdRage = nextNumber - previousNumbe
        // sIdRage = 2
        sIdRage += (sId - previousNumber);           
        count += TimeSpan.FromMinutes(Interval * sIdRage);
        list.FromTime = count.ToString();
        previousNumber = sId; //this line of code has been added for keeping track of previous number , otherwise it will always use previousNumber = 1
        //Note... you need to add a faile to which you are saving the list
        //EG db.Customers.Entry(list) where Customers would be the table
        //in which you would save

        db.Entry(list).State = EntityState.Modified;
        db.SaveChanges();
    }
}