I have this function:
public List<PostIndexResponse> GetPosts(string search, int? categoryId)
{
var currentUserId = HttpContext.Current.User.Identity.GetUserId() ?? "";
var srch = search ?? "";
var posts = _set.Where(x => x.PersonId.Contains(currentUserId) && x.Description.Contains(srch) && x.CategoryId == categoryId).OrderByDescending(x => x.CreatedOn)).ToList();
return posts;
}
I want to have x.CategoryId == categoryId
only if categoryId
is not null. How do I do this without having an if else condition and creating another query based if it is null or not?
CodePudding user response:
I would break it up in to a couple lines something like this (UNTESTED)...
This allows you to conditionally filter on categoryId
and I think it's cleaner and more maintainable than attempting to cram it all in to a single expression. No need to create 2 overlapping expressions
public List<PostIndexResponse> GetPosts(string search, int? categoryId)
{
var currentUserId = HttpContext.Current.User.Identity.GetUserId() ?? "";
var srch = search ?? "";
var query = _set.Where(x => x.PersonId.Contains(currentUserId) && x.Description.Contains(srch));
if (categoryId.HasValue)
query = query.Where(x => x.CategoryId == categoryId);
var posts = query.OrderByDescending(x => x.CreatedOn)).ToList();
return posts;
}
The other option is to replace x.CategoryId == categoryId
with
(categoryId == null || x.CategoryId == categoryId)
But that expression is already getting long and difficult to maintain.