Home > Enterprise >  For loop takes the the max count
For loop takes the the max count

Time:07-31

 private List<SurveyDetail> GetSurveyDetails()
    {
        List<SurveyDetail> surveyDetails = new List<SurveyDetail>();
        SurveyDetail detail = new SurveyDetail();
        int cid = 0;
        for (int i = 1; i < 3; i  )
        {
           detail.choiceId = "1";
           detail.choiceDesc = "tesT";
           detail.questionId = i.ToString();
           surveyDetails.Add(detail);
        }
        return surveyDetails;
    }


 public class SurveyDetail
    {
        public string questionId { get; set; }
        public string choiceId { get; set; }
        public string choiceDesc { get; set; }
    }

when I run the code it question Id always gives me the last number of i that was run for example, in this case, it gives me 2. It gives me 2 on both counts. Where I want the questionid to be 1 in the first count and 2 in the second.

CodePudding user response:

You should move SurveyDetail initialization into the for body

 private List<SurveyDetail> GetSurveyDetails()
    {
        List<SurveyDetail> surveyDetails = new List<SurveyDetail>();
        int cid = 0;
        for (int i = 1; i < 3; i  )
        {
           SurveyDetail detail = new SurveyDetail();//<==NOTE THIS
           detail.choiceId = "1";
           detail.choiceDesc = "tesT";
           detail.questionId = i.ToString();
           surveyDetails.Add(detail);
        }
        return surveyDetails;
    }
  • Related