最近做项目,用到了max,min,average等函数。sql server 的相信很多人会用,而linq的或许很多人比较陌生,下面是我从网上搜集的一个案例,关于linq的几个典型函数,供大家学习。

A.min()函数
min
var categories =
  from p in db.Products
  group p by p.CategoryID into g
  select new {
    CategoryID = g.Key,
     CheapestProducts =
      from p2 in g
       where p2.UnitPrice == g.Min(p3 => p3.UnitPrice)
       select p2
  };

B.max()函数

  //var q = db.Employees.Select(e => e.HireDate).Max();

//var q = db.Products.Max(p => p.UnitsInStock);

var categories =
  from p in db.Products
   group p by p.CategoryID into g
  select new {
     g.Key,
    MostExpensiveProducts =
      from p2 in g
      where p2.UnitPrice == g.Max(p3 => p3.UnitPrice)
      select p2
  };


C.average()函数

var q = db.Products.Average(p => p.UnitPrice);
var q = db.Orders.Select(o => o.Freight).Average();
var categories =
  from p in db.Products
  group p by p.CategoryID into g
  select new {
    g.Key,
    ExpensiveProducts =
       from p2 in g
      where p2.UnitPrice > g.Average (p3 => p3.UnitPrice)
      select p2
   };