我的視圖中有一個 foreach 回圈,我需要它在特定的 order id HTML 部分中寫入資料。問題是如果該部分沒有資料,我不希望看到 HTML 部分。
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>
}
}
有了這個我的輸出,取決于我的串列和輸入資料的順序是這樣的:
<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>
我需要它是這樣的,重要的部分例如“第 2 節”如果沒有資料就不需要寫!:
<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>
uj5u.com熱心網友回復:
我認為您可以將foreach回圈重構為:
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>
}
}
這將根據部分 id 對您的串列進行排序,并且還將檢查串列中是否有任何元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/451553.html
標籤:C# 列表 排序 前锋 asp.net-mvc-5
