如何在ToList()中包含FirstOrDefault()

时间:2018-02-05 10:57:31

标签: asp.net-mvc linq

我想为每个食谱只获得一个文件。

var UploadedFiles = (from rec in db.Recipes
                     join files in db.Files on rec.Id equals files.RecipeId
                     select new
                     {
                         files.Id,
                         files.Path,
                         files.RecipeId,
                         rec.Name,
                         rec.Description,
                         rec.Category,
                         rec.CookTime
                     }).ToList();
return new JsonResult { Data = UploadedFiles, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

2 个答案:

答案 0 :(得分:2)

您可以使用组连接而不是常规连接,我认为它也比前一个答案(使用let)更有效,尽管在这种情况下我并不完全了解EF查询优化

var UploadedFiles = (from rec in db.Recipes
                 join files in db.Files on rec.Id equals files.RecipeId into g
                 let firstFile = g.FirstOrDefault()
                 select new
                 {
                     firstFile.Id,
                     firstFile.Path,
                     firstFile.RecipeId,
                     rec.Name,
                     rec.Description,
                     rec.Category,
                     rec.CookTime
                 }).ToList();

更新

因为我不使用EF,所以我无法确认它是否处理空值,但我被告知它不会删除空值。

var UploadedFiles = (from rec in db.Recipes
                 join files in db.Files on rec.Id equals files.RecipeId into g
                 let firstFile = g.FirstOrDefault()
                 where firstFile != null
                 select new
                 {
                     firstFile.Id,
                     firstFile.Path,
                     firstFile.RecipeId,
                     rec.Name,
                     rec.Description,
                     rec.Category,
                     rec.CookTime
                 }).ToList();

答案 1 :(得分:1)

您可以尝试以下内容......

var UploadedFiles = (from rec in db.Recipes
                 from files in db.Files.FirstOrDefault(f => f.RecipeId == rec.Id)
                 select new
                 {
                     files.Id,
                     files.Path,
                     files.RecipeId,
                     rec.Name,
                     rec.Description,
                     rec.Category,
                     rec.CookTime
                 }).ToList();
return new JsonResult { Data = UploadedFiles, JsonRequestBehavior = 
JsonRequestBehavior.AllowGet };