iT邦幫忙

1

Linq Method GroupBy 的寫法

public class Product
    {
        public string Code{ get; set; }
        public string Name{ get; set; }
        public int QTY{ get; set; }
    }
void Main()
{
	 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 });
        
        //Linq Query
//	 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)};

     //Linq Method
	 var LinqStament = pList.GroupBy(g=>new {g.Code,g.Name})
                            .Select(s=>new {s.Key.Code,s.Key.Name,});
     
	 LinqStament.Dump();
}

想請問各位大大,我在練習LINQ的時候,想要同一個查詢可以Linq Method 跟 Linq Query 都寫出來,但在Method這邊我不太知道要怎麼寫出一樣的查詢
請了解Linq的大大幫解惑,感謝

已經解決
var LinqStament = pList.GroupBy(g => new { g.Code, g.Name }).Select(s => new { s.Key.Code, s.Key.Name,QTY=s.Sum(p=>p.QTY)});

看來是頭腦有點昏了,剛剛鬼打牆一段時間

尚未有邦友回答

立即登入回答