Linq multiple join、GroupBy和OrderBy尝试了我能找到的一切

Linq multiple join、GroupBy和OrderBy尝试了我能找到的一切,linq,Linq,我想按cartID排序结果,因为groupby子句我无法完成 分组后需要排序 要实现您的目标,请替换 var CartItemsGroup = (from Cart in db.BuyOnlineCartMasters // orderby this Cart.CartID descending join CartDetails in db.BuyOnlineCartDetails on Cart.CartID equals CartDetails.CartID

我想按cartID排序结果,因为groupby子句我无法完成


分组后需要排序

要实现您的目标,请替换

var CartItemsGroup = (from Cart in db.BuyOnlineCartMasters // orderby this Cart.CartID descending 
    join CartDetails in db.BuyOnlineCartDetails 
        on Cart.CartID equals CartDetails.CartID

    join ProductMaster in db.tblBuyOnlineMasters.Where(x => x.CompanyID == CompanyID)
        on CartDetails.BuyOnlineID equals ProductMaster.BuyOnlineID

//I tried here did not work ,  orderby Cart.CartID descending

    select new { Cart.CartID, Cart.InvoiceNumber, ProductMaster.CompanyID,
    ProductMaster.Price, ProductMaster.Title, ProductMaster.OfferPrice, 
    CartDetails.SoldPrice, CartDetails.Qty, CartDetails.ShippingStatus, 
    CartDetails.DeliveryStatus, TotalAmt = (CartDetails.Qty * CartDetails.SoldPrice)}

    into x

//I tried here did not work, orderby x.CartID descending

//TODO: where conditions are not set for cart like payment paid etc
    group x by x.CartID)
    .ToList();


首先选择数据,然后按分组。那就行了。我的桌子上有一个样品

group x by x.CartID into g
orderby g.Key descending
select g
来自中的数据
(以DB.GM_顺序从o开始)
将g加入到o.ORDERID等于g.ORDERID的DB.GM_ORDERITEMS中
在g.ITEMID上的DB.GM_项中加入i等于i.ITEMID

o.ORDERIDI希望这也能起作用,我使用了上面的一个,谢谢大家的支持。请欣赏您的评论@arunpasad这个技巧在LINQ to对象中有效,但在其他LINQ提供程序(如LINQ to Entities)中无效。如何在其他列上执行orderby,以备参考。这取决于您是要对组还是组元素进行排序。Ordering按不属于键的列分组并不容易。
group x by x.CartID into g
orderby g.Key descending
select g
from data in
    (from o in DB.GM_ORDER
        join g in DB.GM_ORDERITEMS on o.ORDERID equals g.ORDERID
        join i in DB.GM_ITEM on g.ITEMID equals i.ITEMID
    where o.ORDERID<=11160 /* or any other filter to be applied */
    orderby o.ORDERID descending, i.ITEMCODE ascending /* in your case ORDERID will be CARTID. Continue sorting within the ORDER/CART with a second parameter (in your case can be delivery status) */
    select new { o.ORDERID, i.ITEMCODE, g.ITEMID, Total = (g.CURR_PRICE * g.QTY) }
) select data
into x
group x by x.ORDERID