skip to Main Content
 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.

2

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. Incase you want to use : LINQ

     var result = Enumerable.Range(1, 3).Select(detail => new SurveyDetail
            {
                choiceId = "1",
                questionId = detail.ToString(),
                choiceDesc = "testT",
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search