【问题标题】:C# for loop comparing next value with current valueC# for 循环比较下一个值和当前值
【发布时间】:2013-07-17 03:32:11
【问题描述】:

我在这里有这段代码,基本上我在做一个 for 循环,因为我从数据库中检索记录(使用实体框架)但是当我想使用 if 语句进行比较时出现错误:

       IList<Model.question> lstQuestion = qn.GetRecords(taskID, activityID);

        for(int i = 0 ; i <lstQuestion.Count()-1 ; i++)
        {
             .... //code here

            if(lstQuestion[i].QuestionNo == lstQuestion[i++].QuestionNo) // error at i++
            {
                tb.Text = lstQuestion[i++].QuestionContent;
                sp1.Children.Add(tb);
            }

我试过了

lstQuestion.Count() 代替 lstQuestion.Count()-1;

也不行。

QuestionNo 是我的数据库表中的一列。

完全错误:

当我删除整个 if 语句时,它工作正常。

【问题讨论】:

  • InnerException 说{“指定的视觉对象已经是另一个视觉对象的子对象或 CompositionTarget 的根。”}

标签: c# wpf entity-framework for-loop


【解决方案1】:

您将i 增加三倍。试试这个:

for(int i = 0 ; i <lstQuestion.Count(); i++)
        {
             .... //code here

            if(lstQuestion[i].QuestionNo == 1stQuestion[i+1].QuestionNo) // error at i++
            {
                tb.Text = lstQuestion[i+1].QuestionContent;
                sp1.Children.Add(tb);
            }

【讨论】:

  • 听起来是sp1.Children.Add(tb); 给你带来了麻烦。如果没有在上下文中看到它,我不完全确定你想在那里做什么。 tb 显然已经是别的东西的孩子了。
  • 我没有粘贴完整的代码,因为我认为它不相关,sp1 是我要添加 tb 的堆栈面板的名称。
  • 我删除了 sp1.children.add(tb) 和 tb.text 行但我保留了 if 语句,错误仍然是
  • @user2376998 您的循环不正确。请参阅我的答案以获取正确的循环。但我同意 Bodacious 的观点,即 sp1.Children.Add(tb);也给你添麻烦了。
  • @EhsanUllah 是的,我回答后也想过这个问题,但即使使用count()-1,他似乎仍然有问题。
【解决方案2】:

您在 == 1stQuestion[i] 中有一个数字 1,而不是像其他 lstQuestion[i] 引用中的小写 L。

【讨论】:

    【解决方案3】:

    这应该可以解决您的 if 语句问题。

        for(int i = 0 ; i <lstQuestion.Count()-1; i++)
        {
             .... //code here
    
            if(lstQuestion[i].QuestionNo == 1stQuestion[i+1].QuestionNo) 
            {
                tb.Text = lstQuestion[i+1].QuestionContent;
                sp1.Children.Add(tb);
            }
    

    但我认为你在这条线上遇到了错误

                          sp1.Children.Add(tb);
    

    【讨论】:

      【解决方案4】:

      尝试使用 ++i 而不是 i++。

      IList<Model.question> lstQuestion = qn.GetRecords(taskID, activityID);
      
              for(int i = 0 ; i <lstQuestion.Count()-1 ; i++)
              {
                   .... //code here
      
                  if(lstQuestion[i].QuestionNo == lstQuestion[++i].QuestionNo) // error at i++
                  {
                      tb.Text = lstQuestion[i].QuestionContent;
                      sp1.Children.Add(tb);
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-30
        • 1970-01-01
        • 2020-08-12
        • 2017-11-25
        相关资源
        最近更新 更多