列表填充空数据

时间:2015-11-07 17:19:00

标签: c#

由于我还是C#的初学者,我在代码方面遇到了一些问题。 用户正在填写带有一些问题的富文本框:

List<RichTextBox> boxForQuestions = new List<RichTextBox>();
for (int i = 0; i < numberOfQuestions; i++)
{
       Label labelForEnumeration = new Label();
       labelForEnumeration.Text = (i + 1).ToString();
       labelForEnumeration.Text = labelForEnumeration.Text + ".";
       flowLayoutPanel1.Controls.Add(labelForEnumeration);

       RichTextBox tempBox = new RichTextBox();
       tempBox.Size = new Size(650,60);
       tempBox.Font = new System.Drawing.Font(FontFamily.GenericSansSerif,11.0F);
       flowLayoutPanel1.Controls.Add(tempBox);

       boxForQuestions.Add(tempBox);
}

我将这些问题添加到我的字符串列表中:

List<string> listOfQuestions = new List<string>();
for (int i = 0; i < numberOfQuestions; i++)
{
       listOfQuestions.Add(boxForQuestions[i].Text);
}

现在,我试图在这个函数的某些组中随机化它们:

List<List<string>> questions = new List<List<string>>();
static Random rnd = new Random(); 

public void randomizingQuestions()
{
    for (int i = 0; i < numberOfGroups; i++)
    {
         List<string> groupOfQuestions = new List<string>();
         for (int j = 0; j < numberOfQuestionsPerGroup; j++)
         {
               int index = rnd.Next(listOfQuestions.Count - 1);
               string oneQuestion = listOfQuestions[index];

               foreach (string temp in groupOfQuestions)
               {
                    if (temp != oneQuestion)
                    {
                        groupOfQuestions.Add(oneQuestion);
                    }
               }
         }

         questions.Add(groupOfQuestions);
    }
}

但是,列表是空的,因为当我想将这些问题添加到PDF文件时,文件中没有任何内容:

Document document = new Document(iTextSharp.text.PageSize.LETTER, 20, 20, 42, 35);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFile.FileName, FileMode.Create));
document.Open();

document.Add(new Paragraph("TEST"));

foreach (List<string> question in questions)
{
        document.NewPage();
        foreach (string field in question)
        {
               document.Add(new Paragraph(field));
        }
}

document.Close();

你能告诉我我的错吗?

1 个答案:

答案 0 :(得分:0)

问题是,groupOfQuestions在循环开始时为空,因此其中没有字符串可用,因此,for-each循环中的语句永远不会执行。你可以改用:

if(!groupOfQuestions.Contains(oneQuestion)
{
    groupOfQuestions.Add(oneQuestion);
}

顺便说一句,如果.Add命令已执行,您将得到以下异常:

Collection was modified; enumeration operation may not execute.