ASP.NET MVC 5 : foreach loop sort and write output in specific order

I have a foreach loop in my view and I need it to write data in specific order id HTML sections. The problem is that i don't want HTML section to be seen if there is no data for that section.

int idSection1 = 1;
int idSection2 = 2;
int idSection3 = 3;

@foreach (var item in Model.ItemList)
{
    if (itme.IdSection == idSection1)
    {
        <div>
            <h4>Section 1</h4>
            foreach (var data in Model.ItemList)
            {
                if (data.IdSection == 1)
                {
                    <p>data</p>
                }
                idSection1 = idSection1 + 10;
            }
        </div>
    }

    if (itme.IdSection == idSection2)
    {
        <div>
            <h4>Section 2</h4>
            foreach (var data in Model.ItemList)
            {
                if (data.IdSection == 2)
                {
                    <p>data</p>
                }
                idSection2 = idSection1 + 10;
            }
        </div>
    }

    if (itme.IdSection == idSection3)
    {
        <div>
            <h4>Section 3</h4>
            foreach (var data in Model.ItemList)
            {
                if (data.IdSection == 2)
                {
                    <p>data</p>
                }
                idSection3 = idSection3 + 10;
            }
        </div>
    }
}

And with this my output, depending on my list and in what order data was entered is this:

<h4>Section 2</h4>
    <p>data 1</p>
    <p>data 2</p>
    <p>data 3</p>
    
<h4>Section 1</h4>
    <p>data 1</p>
    
<h4>Section 3</h4>
    <p>data 1</p>
    <p>data 2</p>

And I need it to be this, with important part that for example "Section 2" doesn't need to written if there is no data for it! :

 <h4>Section 1</h4>
    <p>data 1</p>
    
<h4>Section 2</h4>
    <p>data 1</p>
    <p>data 2</p>
    <p>data 3</p>   
    
<h4>Section 3</h4>
    <p>data 1</p>
    <p>data 2</p>


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation