开发者

C#, LInq, Entity Framework 4: Split a table in to a two dimensional array using Linq

I have an Entity like this:

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

So a List produces this JSON (three sizes and three colors

[{"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"}]

However the JavaScript cli开发者_开发技巧ent needs something like this 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"}]]

And this is smack dab in the middle of my Linq query.

How would I construct the Linq query to assemble the two dimensional array from the one dimensional array within Linq?

EDIT: Existing Query:

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

EDIT: Getting Closer:

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}) }),


I haven't tested this, but it's familiar territory and should work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜