如何变量为null选择所有记录,否则选择linq中的过滤记录

时间:2017-06-25 14:00:33

标签: asp.net-mvc linq

我有这个查询,我想要JobID等于JobID变量的选择记录,或者如果JobID为null,请选择所有记录。我该怎么办?

var SearchPost = (from p in db.Posters
                  where p.CityID == CityID && p.PosterOK == 1 && p.PosterName.Contains(strSearch) && p.PosterImageCount > btnImage && p.JobID == JobID
                  join a in db.Likes
                  on p.PosterID equals a.PosterID into LikeSearch
                  join b in db.Comments
                  on p.PosterID equals b.PosterID into CommentSearch
                  select new { 
                    p
                    //For get Count of like
                    , like = LikeSearch.Where(a => a.PosterID == p.PosterID).Count()
                    //For get AVG from Comments
                    , CommentCount = CommentSearch.Where(b => b.PosterID == p.PosterID).Count()
                    , price = (int?)CommentSearch.Select(h => h.Price).Average() ?? 0
                    , quality = (int?)CommentSearch.Select(h => h.Quality).Average() ?? 0
                    , variety = (int?)CommentSearch.Select(h => h.Variety).Average() ?? 0
                   , morality = (int?)CommentSearch.Select(h => h.Morality).Average() ?? 0
             }); 

1 个答案:

答案 0 :(得分:0)

如果有if条件并检查null然后添加该查询?

var SearchPost =  (from p in db.Posters
                           where p.CityID == CityID && p.PosterOK == 1 && p.PosterName.Contains(strSearch) && p.PosterImageCount > btnImage 
                           join a in db.Likes
                           on p.PosterID equals a.PosterID into LikeSearch
                           join b in db.Comments
                           on p.PosterID equals b.PosterID into CommentSearch
                           select new { 
                              p
                              //For get Count of like
                              , like = LikeSearch.Where(a => a.PosterID == p.PosterID).Count()
                              //For get AVG from Comments
                              , CommentCount = CommentSearch.Where(b => b.PosterID == p.PosterID).Count()
                              , price = (int?)CommentSearch.Select(h => h.Price).Average() ?? 0
                              , quality = (int?)CommentSearch.Select(h => h.Quality).Average() ?? 0
                              , variety = (int?)CommentSearch.Select(h => h.Variety).Average() ?? 0
                              , morality = (int?)CommentSearch.Select(h => h.Morality).Average() ?? 0
                           }); 

if(JobID !=null)
{
    var SearchPost1 = SearchPost.Where(p => p.JobID == JobID)
}