0

I have an XML file I am loading and breaking the document down into Ienumerable then putting each element into a label on a winform. sofar I have the following code, which works

public void PopulateGameBoard()
    {
         XDocument gameFiles = XDocument.Parse(Properties.Resources.Jeopardy);

         IEnumerable<string> categories =
             from category in gameFiles.Descendants("category")
             select (string)category.Attribute("name");


         string first = categories.ElementAt(0);
         cat1HeaderLabel.Text = first;
         string second = categories.ElementAt(1);
         cat2HeaderLabel.Text = second;
         string third = categories.ElementAt(2);
         cat3Label.Text = third;
         string fourth = categories.ElementAt(3);
         cat4Label.Text = fourth;
         string fifth = categories.ElementAt(4);
         cat5Label.Text = fifth;

    }

The final product is Jeopardy Game Board where the categories and questions will be pulled from an XML file

This is the first of 5 rows that I will need to do this with (5 lists going into 5 rows). I am wondering if there is a better way to code this where I dont end up with 25 statements assigning a variabel to an ElementAt() and then 25 assignments of that variable.

4

1 回答 1

0

这里我尝试动态创建标签并为其赋值,这是手写代码,所以不保证它会编译,进行必要的更改

public void PopulateGameBoard()
{
     XDocument gameFiles = XDocument.Parse(Properties.Resources.Jeopardy);
     IEnumerable<string> categories =
         from category in gameFiles.Descendants("category")
         select (string)category.Attribute("name");
     Label[] cat1HeaderLabel= new Label[100];  
     int i = 0;
       categories.Each(p =>
       {
           cat1HeaderLabel[i] = new Label();
           cat1HeaderLabel[i].Text = p;
           this.Form.Controls.Add(cat1HeaderLabel[i]);
           i++;
       });
}
于 2012-12-06T07:39:58.167 回答