1

目标

获取并突出显示 a 内小数点之间的最低价格foreach

场景

我正在比较一些市场之间的各种产品价格。结果以 HTML 格式显示table。该表的最后一行包含总价值,即每个市场的每种产品价格的总和。

例如:

                 Market 1    Market 2  
 Xbox 360        US$119,00   US$125,00 
 Playstation 3   US$129,00   US$119,00 
 Total           US$248,00   US$244,00

视图背后的代码是:

@foreach (var item in Model.Collection.Products.DistinctBy(p => p.id))
{
    <tr>
        <td>
            <p>@item.name</p>
        </td>

        @foreach (var market in Model.Markets)
        {
            <td>
                @foreach (var product in Model.Collection.Products.Where
                    (p => p.productId == item.productId && 
                     p.marketId == market.id))
                {
                    <p>@product.price</p>
                }
            </td>
        }
    </tr>
}

<tr>
    @foreach (var market in @Model.Markets)
    {
        <td class="total">
            @{
                decimal totalValue = 
                    Model.Collection.GetTotalPrice(market.marketId);
            }

            @if (totalValue == 0)
            {
                <h2>Unavailable</h2>
            }
            else
            {
                <h2>US$@totalValue</h2>
            }
        </td>
    }
</tr>

到目前为止,一切都很好。现在问题来了:我想突出显示市场之间的最低价格(最低总价) ——我该怎么做?

4

2 回答 2

5

你可以把最低的价格拿出来作为基准。此示例在价格标签lowest上设置一个类别,<p>如果它是<=该特定市场的最低产品价格

@foreach (var market in Model.Markets)
{
    @{ 
        var marketProducts = Model.Collection.Products.Where(p => p.productId == item.productId && p.marketId == market.id).ToList();
        var lowestMarketPrice = marketProducts.Min(p => p.price);
    }
    <td>
        @foreach (var product in marketProducts)
        {
            <p @(product.price <= lowestMarketPrice ? "class=lowest" : "")>@product.price</p>
        }
    </td>
}

根据您的说明,您可以通过以下方式突出显示任何市场中最低的总数

@{ 
    var marketTotals = Model.Markets.ToDictionary(m => m.marketId, m => Model.Collection.GetTotalPrice(m.marketId));
    var lowestTotal = marketTotals.Min(t => t.Value);
}
@foreach (var price in marketTotals)
{
    <td @(price.Value <= lowestTotal ? "class=total-lowest" : "class=total")>
        <h2>@{ price.Value == 0 ? "Unavailable" : String.Format("US${0}", price.Value) }</h2>
    </td>
}
于 2013-08-09T14:07:22.473 回答
1

在渲染输出之前计算最低价格:

@{
var products = Model.Collection.Products.DistinctBy(p => p.id);
decimal[] minimalPrices = new decimal[products.Length];
@for(int i = 0; i < products.Length; i++))
{
  decimal min = Decimal.MaxValue;
  @foreach (var market in Model.Markets)
  {
    //..compute price and compare to min        
  }
  minimalPrices[i] = min;
}
}

.....在渲染中

if( price == minimalPrices[i])
   highlight it
于 2013-08-09T14:16:47.123 回答