将sql转换为Lambda表达式

时间:2013-09-01 00:47:17

标签: sql linq asp.net-mvc-4 razor lambda

盖伊,我需要一个用于此sql语句的Lambda表达式。

select GalleryId, Max(Bid)
from BidModels
where GalleryId in (select GalleryId from BidModels where UserId = (UserId))
group by GalleryId

3 个答案:

答案 0 :(得分:1)

我不明白为什么你需要子查询,因为你可以选择传入UserId = userid的所有Bids。考虑到这一点:

var userid = <whatever>;

var query = from b in BidModels
            where b.UserId = userid
            group by b.GalleryId into g
            select new {Id = g.Key, MaxBid = g.Max(x => x.Bid)};

答案 1 :(得分:0)

以下是如何做到这一点

var galleryIds = (bidModelses.Where(b => b.UserId == [YOURPARAMETER])
                 .Select(b => b.GalleryId));

var query = (bidModelses.Where(bm => galleryIds.Contains(bm.GalleryId))
            .GroupBy(bm => bm.GalleryId)
            .Select(gbm => new {gbm.Key, MaxBid = gbm.Max(p => p.BidId)}));

答案 2 :(得分:0)

感谢您的帮助,这似乎是答案:

from b in BidModels
let  MyGallery = from a in BidModels where a.UserId == (1) select new { a.GalleryId }
where MyGallery.Any()
group b.Bid by b.GalleryId into g
select new 
 { Id     = g.Key, 
   MaxBid = g.Max()
 }