代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

C#,LInq,实体框架4:使用LInq将表拆分为二维数组

  •  0
  • Zachary Scott  · 技术社区  · 14 年前

    我有这样一个实体:

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

    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}) }),
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   John Fisher    14 年前

    我还没有测试过,但这是一个熟悉的领域,应该有用:

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