Linq 分组GoupBy并且求和Sum

 Linq 分组GoupBy并且求和Sum

List<Order> orderList = new List<Order>();
            for (int i = 0; i < 3; i++)
            {
                Order orderEntity = new Order();
                orderEntity.OrderID = 100 + i;
                orderEntity.SellerID = i;
                orderList.Add(orderEntity);
            }

            Order orderEntity2 = new Order();
            orderEntity2.OrderID = 400;
            orderEntity2.SellerID = 4;
            orderList.Add(orderEntity2);

            Order orderEntity3 = new Order();
            orderEntity3.OrderID = 400;
            orderEntity3.SellerID = 4;
            orderList.Add(orderEntity3);


 //查询分组后的结果
            var groupSellerID = from t in orderList
                                group t by new { SellerIDAA = t.SellerID } into g
                                select g;

            //拿到分组中的最大值
            var groupSellerID2 = from t in orderList
                                 group t by new { SellerIDAA = t.SellerID } into g
                                 select new Order
                                 {
                                     SellerID = g.Key.SellerIDAA,
                                     OrderID = g.Max(v => v.OrderID)
                                 };

            //各个分组的最大值相加
            var groupSellerID3 = (from t in orderList
                                  group t by new { SellerIDAA = t.SellerID } into g
                                  select new Order
                                  {
                                      SellerID = g.Key.SellerIDAA,
                                      OrderID = g.Max(v => v.OrderID)
                                  }).Sum(su => su.OrderID);

-----------------------------------------

 public class Order
    {
        public int OrderID { get; set; }
        public int SellerID { get; set; }

    }

==================================================================

//订单总运费
                //按SellerID分组,取每组中运费最大值,最后每组最大值相加。
                decimal tradePostFee = (from t in addTradeAndOrderRequstA.requestOrderAddList
                                   group t by new { SellerIDAA = t.SellerID } into g
                                   select new AddOrderRequest
                                   {
                                       SellerID = g.Key.SellerIDAA,
                                       PostFee = g.Max(v => v.PostFee)
                                   }).Sum(su => su.PostFee);

 

posted on 2022-10-28 17:46  Jankie1122  阅读(28)  评论(0编辑  收藏  举报