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

Time:03-28

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>

CodePudding user response:

I think you can refactor your foreach loop to just this:

var idSection=1;

@foreach (var item in Model.ItemList.OrderBy(x=>x.IdSection))
{
    if(Model.ItemList.Any())
    {
        <div>
            <h4>Section @item.IdSection</h4>
            foreach (var data in Model.ItemList.OrderBy(x=>x.IdSection))
            {
                <p>data @data.IdSection</p>
                idSection = idSection   10;
            }
        </div>  
    }
}

This will sort your list based on the section id and it will also check if there are any elements in the list.

  • Related