用空数据填充的列表

本文关键字:列表 填充 数据 | 更新日期: 2023-09-27 18:20:55

由于我还是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();

你能告诉我我做错了什么吗?

用空数据填充的列表

问题是,groupOfQuestions在循环开始时是空的,因此其中没有可枚举的字符串,因此,每个循环中的语句永远不会执行。您可以使用:

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

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

Collection was modified; enumeration operation may not execute.