linq實現兩表關聯查詢,使用group by進行分組

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.