Lamda表达式,找出查询所有对象集里,对象的数据并进行求和,修改等。

还是先说说实现的场景:

在后端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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值