目标
计算List<T>C# 中每个产品的最终价格。
问题
我需要计算price * quantity一个简单的产品并将结果返回给视图。
看看这个语法:
var productPrice = productsPrices.Find(x => x.productId == 1);
productPrice.finalProductPrice =
(productPrice.promotionalProductPrice != 0 ?
productPrice.promotionalProductPrice :
productPrice.originalProductPrice)
* sessionProducts.Find(x => x.id == 1).quantity;
就在上面传递的代码片段之前,有一个存储产品 id 的字符串,请参见:
string ids = string.Join(", ", sessionProducts.Select(x => x.id));
而且我认为我需要它为列表finalProductPrice中的每个产品设置一个值productsPrices,但我不知道如何执行此操作。
我对这个问题的看法:
我曾认为我可以使用这样的东西:
productsPrices.Find(x => x.productId == productsPrices.Contains(ids))
.finalProductPrice =
(productsPrices.Find(x => productsPrices.Contains(ids))
.promotionalProductPrice != 0 ?
productsPrices.Find(x => productsPrices.Contains(ids))
.promotionalProductPrice :
productsPrices.Find(x => productsPrices.Contains(ids))
.originalProductPrice) *
sessionProducts.Find(x => x.id == 1).quantity;
但是,当然,没有成功 -.Contains()不适用于字符串。
我真正的问题
如何finalProductPrice为我的列表中的每个产品定义权利productsPrices?如何将每个 id 传递string ids [...]给 to x.productId == something?
欢迎提示(例如,不要使用.Find(),.Select()而是使用!)
聚焦代码
按照我ActionResult的发送所有必要信息到我的视图:
比较.cs:
public ActionResult Compare()
{
List<getMarkets_Result> markets = Markets.Build();
SessionStore sessionStore = new SessionStore();
List<getSpecificProductToShoppingList_Result> sessionProducts =
sessionStore.Get("ProductsSummary", "generic");
string ids = string.Join(", ", sessionProducts.Select(x => x.id));
List<getProductsPrices_Result> productsPrices = Products.PricesList(ids);
ListComparisonViewModel listComparisonViewModel =
new ListComparisonViewModel
{
Markets = markets,
SessionProducts = sessionStore.Get("ProductsSummary", "generic"),
ProductsPrices = productsPrices
};
return View(listComparisonViewModel);
}
如有必要,我的productsPrice清单的上下文:
public partial class getProductsPrices_Result
{
public decimal originalProductPrice { get; set; }
public decimal promotionalProductPrice { get; set; }
public decimal finalProductPrice { get; set; }
public string productName { get; set; }
public string marketName { get; set; }
public int productId { get; set; }
public int marketId { get; set; }
}
我制作了一个名为Products(.cs)的模型来执行产品背后的逻辑。该模型具有的第一个(也是唯一一个)方法是CalculateFinalPrice():
public decimal CalculateProductPriceByQuantity(decimal price, int quantity)
{
return price * quantity;
}