1

After I run my query I have got the result into a dataTable as the following (this is only a simplified resultset):

food_cat    food
-----------------------
vegit       carrot
vegit       onion
vegit       tomato
fruit       cherry
fruit       banana
fruit       orange

I want to list that result grouped by food_cat in an unordered list.

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

I have tried some for, if, while controls but could not find a good solution.

zkanoca
  • 8,468
  • 8
  • 42
  • 87

2 Answers2

1

since you don't provide table names etc. i will try to give the answer in general way.

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
  • 154
  • 1
  • 7
0

Thank you @zibidyum, your technic obtained me to reach a solution. But final solution is here:

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

Any better solutions, suggestions and/or ideas are welcome.

zkanoca
  • 8,468
  • 8
  • 42
  • 87
  • `Convert.ToInt32(dt.Rows[i]["food_cat"]))` this suck so much.... EF is a good solution but it is buggy. I was exploring oracle json seems cool, but the varchar2 limit kills everything unless you are on latest 18c – Toolkit Oct 26 '18 at 09:48