Linq Group将项目加入列表

时间:2014-08-13 14:07:25

标签: entity-framework linq join linq-group

这是一个主要的详细信息场景,其中每个TABLE1分配了多个来自TABLE2的行,我想做一些事情:

From a In TABLE1
Group Join c In TABLE2 On c.ID2 Equals a.ID Into Group
Select New ViewModel1 With {
    .COLUMN1 = a.COLUMN1,
    .COLUMN2 = a.COLUMN2,
    .SUBTABLE = New ViewModel2 With {
        .SUBCOLUMN1 = c.SUBCOLUMN1,
        .SUBCOLUMN2 = c.SUBCOLUMN2,
    }
}

这有可能吗?

2 个答案:

答案 0 :(得分:0)

也许以下内容可以帮助您:

class Program
{
    public class A
    {
        public int ID { get; set; }
        public string COLUMN1 { get; set; }
        public string COLUMN2 { get; set; }
    }

    public class B
    {
        public int ID { get; set; }
        public int AID { get; set; }
        public string SUBCOLUMN1 { get; set; }
        public string SUBCOLUMN2 { get; set; }
    }

    static void Main(string[] args)
    {
        var listA = new List<A>{
            new A() { ID = 1, COLUMN1="COLUMN11",COLUMN2 = "COLUMN12"}, 
            new A() { ID = 2 ,COLUMN1="COLUMN21",COLUMN2 = "COLUMN22"}
        };

        var listB = new List<B>()
        {
            new B(){ID=1,AID = 1 },
            new B(){ID=2,AID = 1},
            new B(){ID=3,AID = 1},
            new B(){ID=4,AID = 2},
            new B(){ID=5,AID = 2}
        };

        //Group Join As Method Chain:
        var queryAsMethodChain = listA.GroupJoin(listB, a => a.ID, b => b.AID, (a, t) => new
        {
            ID = a.ID,
            COLUMN1 = a.COLUMN1,
            COLUMN2 = a.COLUMN2,
            SUBTABLE = t.Select(tt => new { tt.SUBCOLUMN1, tt.SUBCOLUMN2 })
        });


        //Group Join As Standard Method
        var queryAsStandardMethod = from a in listA
                                  join b in listB
                                  on a.ID equals b.AID into t
                                  select new
                                  {
                                      ID = a.ID,
                                      COLUMN1 = a.COLUMN1,
                                      COLUMN2 = a.COLUMN2,
                                      SUBTABLE = t.Select(tt => new { tt.SUBCOLUMN1, tt.SUBCOLUMN2 })
                                  };

    }

答案 1 :(得分:0)

你的意思是:

        var foobars = from foo in foolist
                      join bar in barlist on foo.Fooo equals bar.FooBar into t
                      select new
                      {
                          foo.Baar,
                          barbar = from bar in t
                                   select new { bar.FooBar, bar.BarFoo }
                      };

这将(大致)如何进行您所描述的查询。

抱歉,我不得不重读这个问题几次,以确保它被映射到第一个元素。