2016-04-20 107 views
2

我想分組使用LINQ在中繼器中顯示的項目列表。我有一個查詢,幾乎做我需要但不完全。與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

如果我理解正確的話,你不通過意味着組按順序排列。然後後續排序需要使用ThenBy,否則會破壞第一個排序。 – eftpotrm

+0

如果您按照[如何創建嵌套組(C#編程指南)](https://msdn.microsoft.com/en-us/library/bb545974.aspx),您會注意到該語法有點奇怪的,但無論如何,在你的情況下,組CartGroup by CartGroup.Key'應該是由Cart1.Key組成的CartGroup' –

+1

Ivan你發現我的錯誤,那正是問題所在。謝謝。 – sully77

回答

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 
+0

這將列表中的項目分組,但未按上述答案中的Key進行分組。 – sully77

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(); 

結果:

enter image description here