怎么样,我可以在(linq和lambda)中使用select with max,min函数?

时间:2015-03-11 10:00:59

标签: c# linq lambda asp.net-web-api2

我需要使用linq和lambda搜索最大值和最小值。我有sql select,例如:

SELECT 
      [ProdID]
      ,min([APY]) as minAPY
      ,max([APY]) as minAPY
  FROM [dbase].[dbo].[Dept]
  group by ProdID
  order by ProdID 

谢谢你的帮助!

2 个答案:

答案 0 :(得分:3)

查询应该是:

var res = from x in db.Debt
          group x by x.ProdID into y
          orderby y.Key
          select new 
          { 
              ProdID = y.Key, 
              minAPY = y.Min(z => z.APY), 
              maxAPY = y.Max(z => z.APY) 
          };

正如您所看到的,它很好地反映了TSQL查询。唯一重要的"事情是into y之后group(继续查询所必需的)

答案 1 :(得分:0)

试试这个:

var result = from table in ContextDB.Dept 
                   group table by table.ProdID into tableGroup
                   order by table.ProdId
                   select new 
                   {
                        ProdID = tableGroup.Key, 
                        minAPY = tableGroup.Min(item => item.APY), 
                        maxAPY = tableGroup.Max(item => item.APY) 
                   }