考虑foreach循环中的bool值
本文关键字:bool foreach 循环 考虑 | 更新日期: 2023-09-27 18:01:37
对于我期望的人来说,这应该是一些简单的点,但是作为一个前端开发人员,试图在没有c#先验知识的情况下掌握MVC剃须刀,这让我难住了。
我有一个布尔变量hasSecond
,我想在以下foreach
中考虑它:
@foreach (PODO_AcceptRejectReasons reason in reasonList2.Where(e => e.Type == 1))
{
<option data-confirm-type="1" data-confirm-attr="@reason.Attribute" value="@reason.ID">@reason.Text</option>
}
当hasSecond
为true
时,我只想显示@reason.Atrribute
值为'SECOND'的选项,否则不显示这些选项。
谢谢你的帮助!
@foreach (PODO_AcceptRejectReasons reason in reasonList2.Where(e => e.Type == 1))
{
if(hasSecond||reason.Attribute!="SECOND")
{
<option data-confirm-type="1" data-confirm-attr="@reason.Attribute" value="@reason.ID">@reason.Text</option>
}
}
应该可以。我想我之前的逻辑有点错。这将显示所有reason.Attribute
不是SECOND
的option
。如果为 SECOND
,则仅在hasSecond
为true时显示option
。
直接添加到Where语句中:
@foreach (PODO_AcceptRejectReasons reason in reasonList2.Where(e => e.Type == 1 && hasSecond))
{
<option data-confirm-type="1" data-confirm-attr="@reason.Attribute" value="@reason.ID">@reason.Text</option>
}
您可以通过以下方式完成,只需在foreach循环中添加一个if语句,并在where中添加另一个子句。
@foreach (PODO_AcceptRejectReasons reason in reasonList2.Where(e => e.Type == 1 && e.Attribute=="SECOND"))
{
if(hasSecond)
{
<option data-confirm-type="1" data-confirm-attr="@reason.Attribute" value="@reason.ID">@reason.Text</option>
}
}
如果您只想在hasSecond
为假时删除data-confirm-attr="@reason.Attribute"
,您可以使用以下命令:
@foreach (PODO_AcceptRejectReasons reason in reasonList2.Where(e => e.Type == 1))
{
<option data-confirm-type="1" @if(hasSecond) { <text>data-confirm-attr="@reason.Attribute"</text> } value="@reason.ID">@reason.Text</option>
}