获取并突出显示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
View背后的代码是:
@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>
到目前为止,这么好。现在出现了问题:我想强调市场之间的最低价格(最低总价格) - 我该怎么做?
答案 0 :(得分: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>
}
答案 1 :(得分: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