嵌套的SQL查询结果列表
问题描述:
后,我跑我的查询我已经得到了结果到一个DataTable如下面的(这只是一个简单的结果集):嵌套的SQL查询结果列表
food_cat food
-----------------------
vegit carrot
vegit onion
vegit tomato
fruit cherry
fruit banana
fruit orange
我想列出的结果通过food_cat
分组在一个无序列表中。
<h3> Vegit </h3>
<ul>
<li>carrot</li>
<li>onion</li>
<li>tomato</ti>
</ul>
<h3>fruit</h3>
<ul>
<li>cherry</li>
<li>banana</li>
<li>orange</li>
</ul>
我已经尝试了一些for
,if
,while
控制,但无法找到一个很好的解决方案。
答
谢谢@zibidyum,你的技术让我得到了一个解决方案。但最终的解决办法是:
public bool firstcat; // defined at before Page_Load method
public int temp_cat; // defined at before Page_Load method
for (int i = 0; i < dt.Rows.Count; i++)
{
if (temp_cat != Convert.ToInt32(dt.Rows[i]["food_cat"]))
{
if (i > 0 && !firstcat)
content.InnerHtml += "</ul>"; //solution's most critic point is here
content.InnerHtml += "<ul>"
}
content.InnerHtml += String.Format("<li>{0}</li>", dt.Rows[i]["food"].ToString());
temp_cat = Convert.ToInt32(dt.Rows[i]["food_cat"]);
}
欢迎任何更好的解决方案,建议和/或想法。
答
因为你不提供表名等我会尽量给出一般的答案。
string previous_food_cat = '';
bool firstEntrance = true
while(trace resultSet until no elements left)
{
if resultSet.food_cat != previous_food_cat //check if food_cat value changed
{
if (!firstEntrance) //if not first entrance close the <ul> tag before opening new one
{
print </ul>
}
print <h3> resultSet.food_cat </h3> //open new <h3> tag
print <ul> //open new <ul> tag
previous_food_cat = resultSet.food_cat //update previous_food_cat for new food_cat value
firstEntrance = false //set firstEntrance false so that ul tqags should be closed
}
print <li> resultSet.food </li>
}
您是否想要在sql级别或演示级别生成UL/LI元素? – gh9
@ gh9在演示级别。但为什么不在sql级别,如果它会更快 – zkanoca
看看嵌套中继器:http://*.com/questions/3571363/nested-repeaters-in-asp-net –