2012-07-13 106 views
3

有一個T-SQL查詢:如何獲得一個類似於tsql查詢的lambda查詢?

select [ProductNumber] ,max([ProductRevNumber]) 
from Products 
group by [ProductNumber] 

嘗試LINQ查詢:

ProductsDBContext.Products.GroupBy(x => x.ProductRevNumber) 
          .Select(group => ProductNumber, 
              ProductRevNumber = group.Max(x => x.ProductRevNumber)); 

拉姆達查詢不起作用。

回答

6

我想這是你所追求的:

var latestProducts = ProductsDBContext.Products 
    .GroupBy(p => p.ProductNumber).Select(g => new 
    { 
     ProductNumber = g.Key, 
     MaxProductRevNumber = g.Max(p => p.ProductRevNumber)) 
    }); 
+0

是什麼g.Key代表什麼?這是一個特殊的關鍵字或某種類型? – dotnetN00b 2012-07-13 17:25:15

+0

g.Key是您分組的字段的值(即p.ProductNumber)。 – 2012-07-13 17:29:46

2
from p in db.Products 
group p by p.ProductNumber into g 
select new 
{ 
    ProductNumber = g.Key, 
    ProductRevNumber = g.Max(p => p.ProductRevNumber) 
};