现在的位置: 首页 > 综合 > 正文

linq实现两表关联查询,使用group by进行分组

2012年11月08日 ⁄ 综合 ⁄ 共 1082字 ⁄ 字号 评论关闭

 FamilyAccountDataContext db = new FamilyAccountDataContext();//数据库实体上下文

     //linq实现两表关联查询,使用group by进行分组,group和by之间放你后面要select的对象(如果只有一个字段,可以直接写,如果有多个可以像我一样使用匿名对象)

    //select的时候也使用匿名对象的方式,并可以命名(如:totalExpense);

            var temp = from a in db.AccountTable
                       join p in db.InOrOutProjectTable
                       on a.InOrOutProjectID equals p.ID
                       where p.ProjectType == false & a.Date >= dateStart & a.Date < dateEnd
                       group new { p.ProjectName, a.Amount } by p.ProjectName into g

                       select new { g.Key, totalExpense = g.Sum(x => x.Amount) };

   //这里使用强类型的对象封装上面得到的temp里的字段,并加入到泛型集合中作为repeater控件的数据源

            List<Common.TotalAmountObj> list = new List<Common.TotalAmountObj>();
            foreach (var item in temp)
            {
                Common.TotalAmountObj totalExpense = new Common.TotalAmountObj();
                totalExpense.ProjectName = item.Key;
                totalExpense.Amount = item.totalExpense;
                list.Add(totalExpense);
            }
            this.repeaterExpenseReport.DataSource = list;
            this.repeaterExpenseReport.DataBind();

抱歉!评论已关闭.