【发布时间】:2020-12-05 00:35:16
【问题描述】:
我正在尝试过滤显示在我的应用程序中的帖子。一切都按预期进行,但我有一个小问题。用户可以选择他所遵循的教育和职业。如何根据获得的数组进行过滤?我试过这样的东西,但感觉很难看。如果我在我的 Filter 类中设置更多的数组,比如 Language[].. 它会变得更加混乱。我可以做点简单的事吗?
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);
}
}
【问题讨论】:
标签: c# .net asp.net-web-api asp.net-core-webapi