我正在尝试使用LINQ对项目列表进行分组,以便在转发器中显示。我有一个查询,几乎可以做我需要的但不完全。
我的数据看起来像
Cart object
{ID: 10, isInventory: True, Pricing: 4},
{ID: 10, isInventory: True, Pricing: 20},
{ID: 10, isInventory: False, Pricing: 5},
{ID: 10, isInventory: False, Pricing: 23},
{ID: 74, isInventory: False, Pricing: 7}
我希望按isInventory分组,然后按ID分组。目前我有一个接近但仍然不正确的查询。
var grouped = from cart in shoppingCart.Cart
group cart by cart.IsInventoryStorage into Cart1
from CartGroup in
(from cart in Cart1
group cart by cart.BranchID)
group CartGroup by CartGroup.Key;
看起来它已正确分组,但isInventory上的Keys
,我理想地希望它为key.isInventory
,然后每个组按key.ID
排序
谢谢
答案 0 :(得分:2)
这可以在查询语法中使用orderby
来完成。请注意,后续排序条件通过逗号分隔。
void Main()
{
var cart = new List<Cart>();
cart.Add(new Cart { ID = 10, isInventory = true, Pricing = 4 });
cart.Add(new Cart { ID = 10, isInventory = true, Pricing = 20});
cart.Add(new Cart { ID = 10, isInventory = false, Pricing = 5});
cart.Add(new Cart { ID = 10, isInventory = false, Pricing = 23});
cart.Add(new Cart { ID = 74, isInventory = false, Pricing = 7});
var grouped = from c in cart
orderby c.isInventory, c.ID
select c;
grouped.Dump();
}
public class Cart
{
public int ID { get; set; }
public bool isInventory { get; set; }
public int Pricing { get; set; }
}
这样输出数据:
10 False 5
74 False 7
10 False 23
10 True 4
10 True 20
答案 1 :(得分:1)
var cart=new []{
new {ID= 10, isInventory= true, Pricing= 4},
new {ID= 10, isInventory= true, Pricing= 20},
new {ID= 10, isInventory= false, Pricing= 5},
new {ID= 10, isInventory= false, Pricing= 23},
new {ID= 74, isInventory= false, Pricing= 7}
};
var results=cart.GroupBy(c=>c.isInventory)
.SelectMany(grp1=>grp1.GroupBy(th=>th.ID),(grp1,grp2)=>new {grp1=grp1,grp2=grp2})
.GroupBy(temp0=>temp0.grp1.Key,temp0=>temp0.grp2)
.Dump();
结果: