How to limit a LINQ left outer join to one row

后端 未结 4 733
南方客
南方客 2020-12-13 12:53

I have a left outer join (below) returning results as expected. I need to limit the results from the \'right\' table to the \'first\' hit. Can I do that somehow? Currently,

4条回答
  •  失恋的感觉
    2020-12-13 13:32

    Use an inner query. Include DefaultIfEmpty for the case of no photo and orderby for the case of more than one. The following example takes the photo with the greatest id.

    var query = 
        from i in db.items
        let p = from p in db.photos where i.id == p.item_id orderby p.id select p).DefaultIfEmpty().Last()
        orderby i.date descending
        select new {
          itemName = i.name,
          itemID = i.id,
          id = i.id,
          photoID = p.PhotoID
        };
    

    If you need to handle the case of no photo specially, you can omit DefaultIfEmpty and use FirstOrDefault/LastOrDefault instead.

提交回复
热议问题