LINQ TO SQL: Group By 與 Sum

  • 77040
  • 0
  • C#
  • 2008-05-03

SQL to LINQ : Group By 與 Sum

網友在【微軟技術社群討論區】遇到的【LINQ 的問題】,將下列  SQL 語法轉換為 LINQ 語法使用:

 

SELECT   Code, Name, sum(QTY)
FORM     Product
GROUP BY Code, Name

LINQ 語法應用:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;

public partial class Default2 : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Product> pList = new List<Product>();
        pList.Add(new Product() { Code = "A", Name = "A1", QTY = 3 });
        pList.Add(new Product() { Code = "A", Name = "A2", QTY = 3 });
        pList.Add(new Product() { Code = "A", Name = "A1", QTY = 4 });
        pList.Add(new Product() { Code = "A", Name = "A3", QTY = 1 });
        pList.Add(new Product() { Code = "A", Name = "A2", QTY = 8 });

        var linqStament = from p in pList 
                          group p by new { p.Code, p.Name } into g
                          select new { Code = g.Key.Code, Name = g.Key.Name, QTY = g.Sum(p => p.QTY) };

        foreach (var query in linqStament)
        {
            string s = string.Format("Code: {0}, Name: {1}, QTY={2} <BR />", query.Code, query.Name, query.QTY);
            Response.Write(s);
        }                          
    }

    public class Product
    {
        public string Code{ get; set; }
        public string Name{ get; set; }
        public int QTY{ get; set; }
    }
}


結果輸出如下:
Code: A, Name: A1, QTY=7
Code: A, Name: A2, QTY=11
Code: A, Name: A3, QTY=1