簡體   English   中英

SQL查詢結果的嵌套列表

[英]Nested list of SQL query result

運行查詢后,將結果保存到dataTable中,如下所示(這只是簡化的結果集):

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>

我已經嘗試了一些forifwhile控制,但無法找到一個很好的解決方案。

由於您不提供表格名稱等。我將嘗試以一般方式給出答案。

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>
}

謝謝@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"]);
}

歡迎任何更好的解決方案,建議和/或想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM