-1

我正在尝试获取一个类中的数组,然后使用 foreach 语句将值迭代到表中。

我的班级设置如下:

public class items
{
   private string[] list;

   public items()
   {
      list[0] = "apples";
      list[1] = "oranges";
      list[2] = "grapes";
      list[3] = "bananas";
   }
}

在我的page_load事件中,我试图打电话给班级:

list fruit = new list();

StringBuilder sb = new StringBuilder();

sb.Append("<table id=\"items\">");
sb.Append("<tr>");
sb.Append("<th>Item</th>");
sb.Append("<th>Description</th>");
sb.Append("<th>Unit Cost</th>");

foreach(string fruit in list)
{
   sb.Append(String.Format("{0}", items.fruit));
}

我是使用foreach循环的新手,它真的很混乱。如果我走在正确的轨道上,我希望能有所了解。

谢谢。

4

5 回答 5

1

如果您想围绕水果列表构建 HTML 表格的标记,您应该将在每个单独项目周围进行标记的部分也放入循环中:

 sb.Append("<table id=\"items\">");
 sb.Append("<tr>");
 sb.Append("<th>Item</th>");
 sb.Append("<th>Description</th>");
 sb.Append("<th>Unit Cost</th>");
 sb.Append("</tr>");
 foreach(var fruit in list) { // Use "var" or the exact type for the fruit
     sb.Append("<tr>");
     // I am assuming here that the fruit has Description and Cost.
     // You may need to replace these names with names of actual properties
     sb.Append(String.Format("<td>{0}</td>", fruit.Description));
     sb.Append(String.Format("<td>{0}</td>", fruit.Cost));
     sb.Append("</tr>");
 }
sb.Append("</table>");
于 2013-03-01T17:21:45.897 回答
0

你的代码有一些问题。首先,items.list在课堂之外无法访问,因此无法在您的事件items中遍历它。page_load您必须使其可访问:

public class items
{
   private string[] list;

   public string[] List
   {
      get { return list; }
   }

   // ...
}

现在,您将能够items像在上一样实例化您的类page_load

items fruit = new items();

并遍历你的类的List属性:items

foreach(string f in fruit.List)
{
   sb.Append(String.Format("{0}", f));
}
于 2013-03-01T17:22:56.223 回答
0

使用Linq:假设你的数组是水果

fruit.ToList().ForEach(f=> sb.Append(String.Format("{0}", f));

理想情况下,如果您有description并且unitCost在您的列表中,您可以将所有<tr>标签添加到表格正文中,例如;

StringBuilder sb = new StringBuilder();
sb.Append("<table id=\"items\">");
sb.Append("<tr><th>Item</th><th>Description</th><th>Unit Cost</th></tr>");

newList.ToList()
 .ForEach(f=> 
          sb.Append(String.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", 
                         f.item, f.desc, f.unitCost))
         );
sb.Append("</table>");
于 2013-03-01T17:23:35.520 回答
0

你想要的是这样的:

sb.Append("<table id=\"items\">");
sb.Append("<tr>");
sb.Append("<th>Item</th>");
sb.Append("<th>Description</th>");
sb.Append("<th>Unit Cost</th>"); 
sb.Append("</tr>");
foreach(string fruit in list)
{
   sb.Append("<tr>");
   sb.Append(String.Format("{0}", fruit));
   sb.Append("description");
   sb.Append(String.Format("2p");
   sb.Append("</tr>");
}
sb.Append("</table>");
于 2013-03-01T17:17:37.057 回答
0

尝试

foreach(string s in fruit)
{
    sb.Append(String.Format("{0}", s));
{
于 2013-03-01T17:19:10.340 回答