2017-06-25 51 views
0

私はこのクエリを持っており、JobIDの等しい変数、またはJobIDがnullの場合はすべてのレコードを選択します。どうしたらいいですか?変数がnullの場合どのようにすべてのレコードを選択するelse linqでフィルタリングされたレコードを選択

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 
      }); 

答えて

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) 
} 
+1

ありがとうございました。それは非常にうまくいく;) – sadegh

関連する問題