简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM