还是先说说实现的场景:
在后端C#获取COOKIE,序列化COOKIE字符串,同时,把选中的产品
挑出来,并求总数,总计。
public static BuyInfoJson GetBuyInfoJson() {
//1.获取cookie
//2.序列化cookie
//3.去掉没选中的
//4.解码
BuyInfoJson buyInfoJson = new BuyInfoJson();
string CartItemsString = HttpContext.Current.Request.Cookies["CartItems"].Value;
List<CartItem> cartItems = new List<CartItem>();
cartItems = OrderHandler.Unitility.JSONStringToList<CartItem>(CartItemsString);
buyInfoJson.H5CartItems = cartItems.FindAll(cartItem => cartItem.isChecked == "checked");
buyInfoJson.H5Amount = buyInfoJson.H5CartItems.Sum(f => f.qty);
buyInfoJson.H5TotalPrice = (buyInfoJson.H5CartItems.Sum(f => f.qty * f.price)).ToString();
buyInfoJson.H5CartItems.ForEach(i => {
i.productName = HttpUtility.UrlDecode(i.productName);
i.color = HttpUtility.UrlDecode(i.color);
});
return buyInfoJson;
}
1,我们获取COOKIE
string CartItemsString = HttpContext.Current.Request.Cookies["CartItems"].Value;
2,我们把COOKIE字符串序列化为对象集
cartItems = OrderHandler.Unitility.JSONStringToList<CartItem>(CartItemsString);
3,我们用LAMDA表达试,FindAll找出所有“选中”的产品对象(cartItem)
buyInfoJson.H5CartItems = cartItems.FindAll(cartItem => cartItem.isChecked == "checked");
4,我们计算对象集里,所有的订购数量
buyInfoJson.H5Amount = buyInfoJson.H5CartItems.Sum(f => f.qty);
5,我们通过Sum方法,计算所有对象的总金额
buyInfoJson.H5TotalPrice = (buyInfoJson.H5CartItems.Sum(f => f.qty * f.price)).ToString();
6,再通过ForEach,把所有属性都更新一下。
buyInfoJson.H5CartItems.ForEach(i => {
i.productName = HttpUtility.UrlDecode(i.productName);
i.color = HttpUtility.UrlDecode(i.color);
});
虽然这些LAMDA表达式可以用其它方法实现,但确实看起来整洁。
————————————————
版权声明:本文为CSDN博主「weixin_44019016」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44019016/article/details/88916684