2010-11-10 75 views
0

二維陣列我有一個實體是這樣的:C#,LINQ,實體框架4:分割表中,以使用LINQ

public class Category 
{ 
    public int classid {get;set;} 
    public int itemid {get;set;} 
    public string label {get;set;} 
} 

因此,一個列表生成此JSON(三種尺寸和三種顏色

[{"classid":1,"itemid":1,"label":"Small"}, 
{"classid":1,"itemid":2,"label":"Medium"}, 
{"classid":1,"itemid":3,"label":"Large"}, 

{"classid":2,"itemid":1,"label":"Blue"}, 
{"classid":2,"itemid":2,"label":"Green"}, 
{"classid":2,"itemid":3,"label":"Red"}, 

{"classid":3,"itemid":1,"label":"Tee"}, 
{"classid":3,"itemid":2,"label":"Golf"}, 
{"classid":3,"itemid":3,"label":"Dress"}] 

但是JavaScript客戶端需要這樣的myarray[][].label

[[{"itemid":1,"label":"Small"}, 
    {"itemid":2,"label":"Medium"}, 
    {"itemid":3,"label":"Large"}], 

[{"itemid":1,"label":"Blue"}, 
    {"itemid":2,"label":"Green"}, 
    {"itemid":3,"label":"Red"}], 

[{"itemid":1,"label":"Tee"}, 
    {"itemid":2,"label":"Golf"}, 
    {"itemid":3,"label":"Dress"}]] 

而且這是在我的Linq查詢的中間點擊。

我該如何構建Linq查詢來從Linq中的一維數組中組裝二維數組?

編輯:現有的查詢:

... 
CATS = (from myP in myProduct.ProductCategories 
     select new ProductCategory 
     { 
      classid = myP.classid, 
      itemid = myP.itemid, 
      label = myP.label 
     }), 
... 

編輯:越來越近:

CATS = (from myP in myProduct.ProductCategories 
     group myP by myP.classid into groups 
     select new resultClass 
     { classid = groups.Key, 
       opts = groups.Select(x => 
       new ProductOption 
       { itemid = x.itemid, 
       label = x.label}) }), 
+0

向我們展示您現有的查詢,我們將嘗試修復它以滿足新的要求。 – LukeH 2010-11-10 01:39:53

+2

這將與GroupBy(item => item.classid)的東西,但沒有你目前的查詢,我不會找出其餘的會是什麼。 – tster 2010-11-10 01:41:44

回答

1

我沒有測試過這一點,但它是自己熟悉的領域,並應工作:

IEnumerable<Category> items = ...; 
var groups = items.GroupBy(x => x.classid); 
var arrays = groups.Select(x => 
    x.Select(y => new { itemid = y.itemid, label = y.label }).ToArray() 
).ToArray(); 
+0

我最終試圖在問題中發佈。我的版本接近但不是那裏。 – 2010-11-10 02:45:23

+0

在查詢btw中不能做.ToList,ToArray等,至少不是這個。它正在構建一個查詢以便稍後進行過濾。 – 2010-11-10 02:49:32