比较foreach中的多个字符串

时间:2017-04-02 06:57:13

标签: c# razor

我正在为酒店做一些编程。如果已经预订,他们想要一封电子邮件收据。

我正在使用名为@GuaranteePolicy

的剃刀合并域

客人可以预订1间或多间客房。如果预订了多个房间,则必须在每个房间设置GuaranteePolicy。但如果每个房间的GuaranteePolicy相同,我必须在页脚中打印GuaranteePolicy。

因此,我看到它必须比较每个房间中的所有GuaranteePolicy合并域,并查看它们是否包含相同的文本?那我不知道怎么解决。

我遍历多个房间,如果GuaranteePolicy不同则打印。这很好用:

@if (!string.IsNullOrWhiteSpace(room.GuaranteePolicy))
{
    <tr>
        <th>
            <span><strong>GuaranteePolicy:</strong></span>
        </th>
    </tr>
    <tr>
        <th>
            <span>@room.GuaranteePolicy</span>
        </th>
    </tr>
}

但是如何比较多个room.GuaranteePolicy中的文字并检查每个房间的文字是否相同?

 @if (room.GuaranteePolicy == ? )
{
    <tr>
        <th>
            <span>@room.GuaranteePolicy</span>
        </th>
    </tr>
    <tr>
         <th>
            <span>@room.GuaranteePolicy</span>
         </th>
    </tr>
}

3 个答案:

答案 0 :(得分:0)

在控制器中创建一个函数,检查所有房间是否具有相同的策略,并将模型中的属性指定为true或false:

public class RoomsModel{
public bool SamePolicy ...
public .......  Rooms ...
}

然后检查cshtml中该属性是否为true

if(Model.SamePolicy){
<footer>....
 }

答案 1 :(得分:0)

为了确定所有房间是否具有相同的GuaranteePolicy属性值,您应该使用该信息准备 ViewModel ,然后将其发送到 View

简化房间类:

public class Room
{
    public string GuaranteePolicy { get; set; }
}

您的控制器内的Loginc返回显示信息的View:

List<Room> rooms = GetSelectedRooms(); //example

bool samePolicy = false;
var firstRoom = rooms.FirstOrDefault();
if (firstRoom != null)
{
    samePolicy = rooms.All(r => r.GuaranteePolicy == firstRoom.GuaranteePolicy);
}

//Attach samePolicy onto ViewModel or ViewBag so you can use it inside Razor view

答案 2 :(得分:0)

如果我理解你的问题,我不是百分之百确定,但简而言之,你想检查以下内容:你的模型包含多个预订,每个预订可能有也可能没有GuaranteePolicy 。您想要检查它们是否已设置,然后它们都是相同的,并且只有在这是真的时才呈现页脚。您可以像下面这样解决它:

@{
    string firstGuaranteePolicy = Model.Bookings.Select(b => b.GuaranteePolicy).FirstOrDefault();
    bool areAllTheSame = Model.Bookings.Select(b => b.GuaranteePolicy).All(val => val == firstGuaranteePolicy);
}

@if (areAllTheSame)
{
    <tfoot>
    ...
    </tfoot>
}

因此,您只需提取第一个GuaranteePolicy值(我假设您可以通过属性Bookings导航到它们,根据您的模型结构修改它们),如果所有值都相同第一个,然后所有这些都是相同的。

相关问题