如何选择每个id linq的第一行

时间:2014-03-27 12:50:09

标签: linq asp.net-mvc-4

所以我有几张桌子,我希望内部加入它的信息两个创建  新对象。但我有点麻烦。

我的一个表有一对多的连接,当linq请求时,它  给我比我想要的更多结果,他只是复制信息。我需要  请求类似这样的内容:

IPagedList<HelperListings> srch = (from l in db.gp_listing
                                  where l.DateCreated > weekago

                                  join lp in db.gp_listing_photo on l.Id equals lp.ListingId
                                  join loc in db.gp_location on l.LocationId equals loc.Id

                                  orderby l.DateCreated ascending
                                  select new HelperListings { id = l.Id, HouseNumber = l.HouseNumber,ListingPrice = l.ListingPrice, PhotoUrl = lp.PhotoUrl.First(), AreaStateCode = loc.AreaStateCode }).ToList().ToPagedList(page ?? 1, 15); 

PhotoUrl = lp.PhotoUrl.First()我需要这样的东西,但我没有任何想法如何去做。需要你的帮助。

1 个答案:

答案 0 :(得分:0)

更新:

根据您的评论,您至少有两个选项:1。使用分组依据并仅选择每个组中的第一个PhotoUrl,或者2.不要加入gp_listing_photo表避免重复的行,并使用子查询只获取第一个PhotoUrl。后者的例子:

IPagedList<HelperListings> srch = 
                    (from l in db.gp_listing
                     where l.DateCreated > weekago
                     join loc in db.gp_location on l.LocationId equals loc.Id
                     orderby l.DateCreated ascending
                     select new HelperListings 
                                { 
                                    id = l.Id, 
                                    HouseNumber = l.HouseNumber,
                                    ListingPrice = l.ListingPrice, 
                                    PhotoUrl = (from lp in db.gp_listing_photo where l.Id = lp.ListingId select lp.PhotoUrl).FirstOrDefault(), 
                                    AreaStateCode = loc.AreaStateCode 
                                }
                    ).ToList().ToPagedList(page ?? 1, 15); 

如何在LINQ查询后简单地附加.Distinct()以避免重复数据:

IPagedList<HelperListings> srch = 
                (from l in db.gp_listing
                 where l.DateCreated > weekago

                 join lp in db.gp_listing_photo on l.Id equals lp.ListingId
                 join loc in db.gp_location on l.LocationId equals loc.Id

                 orderby l.DateCreated ascending
                 select new HelperListings 
                            { 
                                id = l.Id, 
                                HouseNumber = l.HouseNumber,
                                ListingPrice = l.ListingPrice, 
                                PhotoUrl = lp.PhotoUrl, 
                                AreaStateCode = loc.AreaStateCode 
                            }
                ).Distinct().ToList().ToPagedList(page ?? 1, 15); 

供参考:LINQ Select Distinct with Anonymous Types