I'm trying to filter the posts that are displayed in my application. Everything goes like expected, but I have a small issue. A user can choose the education(s) and profession(s) he follows. How can I filter based on the arrays I get? I tried something like this, but it feels ugly. If I set more arrays in my Filter class like Language[].. It wil get more messy. Can I do something easier?
public class Filter
{
public string[] Education { get; set; }
public string[] Profession { get; set; }
public int PageIndex { get; set; }
}
public PaginatedResults<Post> FilterPosts(Filter filter)
{
// Both Education and Profession arrays are empty, we just return all the posts
if(filter.Profession.Any(prof => prof == null) && filter.Education.Any(study => study == null)) {
var posts1 = _dbContext.Posts.AsEnumerable();
return _searchService.Pagination<Post>(posts1, filter.PageIndex);
}
else
{
// Can this be simplified? Sometimes the Education array is empty and sometimes Profession array. User can choose
IEnumerable<Post> posts = null;
if(filter.Profession.Any(prof => prof == null))
{
posts = _dbContext.Posts.Where(post => filter.Education.Contains(post.Education)).AsEnumerable();
}
else if(filter.Education.Any(study => study == null))
{
posts = _dbContext.Posts.Where(post => filter.Profession.Contains(post.Profession)).AsEnumerable();
}
else
{
posts = _dbContext.Posts.Where(post => filter.Profession.Contains(post.Profession) && filter.Education.Contains(post.Education)).AsEnumerable();
}
return _searchService.Pagination<Post>(posts, filter.PageIndex);
}
}
