Search code examples
c#asp.netasp.net-mvcentity-frameworklinq-to-entities

How to add new Items to an Existing List c#?


I am Uploading an Excel file and after reading that file getting result in this.

 var data = from c in excel.Worksheet<QuestionMaster>()
            select new
            {
              c.Questionname,
              c.Answer1,
              c.Answer2,
              c.Answer3,
              c.Answer4,
              c.CorrectAnswer,
            };

Now I need to check that any of the Column in uploaded data should not be null

For that My Code is:
Question Master is the Model Class

QuestionMaster questions = new QuestionMaster();
QuestionMaster temp = new QuestionMaster();
List<QuestionMaster> ques = new List<QuestionMaster>();//
  foreach (var item in data)
   {
      int i = 0;
     if (item.Questionname == null || item.Answer1 == null || item.Answer2 == null ||   item.Answer3 == null || item.Answer4 == null || item.CorrectAnswer == null)
      {
          if (item.Questionname != null)
           temp.Questionname = item.Questionname.Trim();                            
         else
           temp.Questionname = "Question Name not Found in Uploaded Excel File";                            
         if (item.Answer1 != null)
           temp.Answer1 = item.Answer1.Trim();                            
         else
           temp.Answer1 = "Answer 1 Not Found in Uploaded Excel File";                            
                       \\Some more Couple of If-Else Conditions

ques.Add(temp);
      }

Now the Problem is :
Suppose I got three Different Rows in which their are Some Null Columns and the above conditions got true.

When ques.add(temp) runs 2nd or 3rd Time it overwrite the other previously added List Items but the count of the number of the items added in the List remain same.
It means it is overwriting the whole list with the current data in the temp.

Please tell me where I am getting wrong.

Thanks in Advance!!!


Solution

  • you need to be creating a new object in your loop every time, currently it's outside your loop so the original object keeps changing

      foreach (var item in data)
       {
         QuestionMaster temp = new QuestionMaster();
    
       }