说明:数据库以northwind为准
- 目的:选出每个类别中价格最高的一种产品,(要求能打印出产品明细):(三种写法)
- 先进性分组,然后对分组中的每个组进行lamda选择(这种方法直接选出最高价格,而不是对象
var m = from u in entities.Products group u by u.CategoryID into g orderby g.Key select new { g.Key, HignPrice = g.Max(c => c.UnitPrice) };
2. 分组后,选出价格最高的产品(注意:是对象,而不仅仅是价格)
var v = from u in entities.Products //let Names=u.ProductName group u by u.CategoryID into g orderby g.Key select new { g.Key, HignProduct = (from n in g where n.UnitPrice==g.Max(c=>c.UnitPrice) select n).FirstOrDefault() }; foreach (var vv in v) Console.WriteLine(vv.Key + " " + vv.HignProduct.ProductName + " " + vv.HignProduct.UnitPrice);
3. 和上一个基本上差不多,但也算是一个把
var v = from u in entities.Products group u by u.CategoryID into g orderby g.Key select new { g.Key, HignProduct = from n in g where n.UnitPrice==g.Max(c=>c.UnitPrice) select n }; foreach (var vv in v) Console.WriteLine(vv.Key + " " + vv.HignProduct.First().ProductName + " " + vv.HignProduct.First().UnitPrice);