c# - 如何用枚举过滤布尔字段?
问题描述
我有一个 ASP.NET Core 应用程序。
我有一个带有查询方法的存储库。我有AlertStatusEnum
,像这样:
public enum AlertStatusEnum
{
/// <summary>
/// Alerts where done is true
/// </summary>
Done = 1,
/// <summary>
/// Alerts where done is false
/// </summary>
NotDone,
/// <summary>
/// Returns complete list of Alerts either done or NotDone
/// </summary>
All
}
我有一个这样的查询方法:
public async Task<List<Alert>> GetAllAlertsForOrganisation(int organisationId, DateTime? beginDate, DateTime? endDate, AlertStatusEnum statusEnum)
{
return await GetAlerts(i => i.OrganisationId == organisationId
&& (endDate == null || i.CreatedAt <= endDate)
&& (beginDate == null || i.CreatedAt >= beginDate)
&& i.IsDone)
.ToListAsync();
}
IsDone
看起来像这样:
public bool IsDone { get; set; }
所以我唯一想要的是:
- 如果
statusEnum
-parameter 为AlertStatusEnum.Done
,则仅返回具有IsDone
==true的警报 - 如果
statusEnum
-parameter 是AlertStatusEnum.NotDone
,则仅返回具有IsDone
==false的警报 - 如果
statusEnum
-parameter 是AlertStatusEnum.All
,则返回所有警报,尽管有IsDone
-property 的值。
但是如何做到这一点?
解决方案
使用以下代码段,您可以根据statusEnum
-parameter 过滤数据:
public async Task<List<Alert>> GetAllAlertsForOrganisation(int organisationId, DateTime? beginDate, DateTime? endDate, AlertStatusEnum statusEnum)
{
var isDone = statusEnum == AlertStatusEnum.Done;
return await GetAlerts(i => i.OrganisationId == organisationId
&& (endDate == null || i.CreatedAt <= endDate)
&& (beginDate == null || i.CreatedAt >= beginDate)
&& (i.IsDone == isDone || statusEnum == AlertStatusEnum.All))
.ToListAsync();
}
推荐阅读
- javascript - JQuery AJAX 调用多次调用 URI,随调用扩展
- appium-ios - 如何滑动iOS模拟器屏幕
- r - R - 通过多个 URL 抓取网页?带着 rvest 和 purrr
- android - 带有静态图像的 HorizontalScrollView
- python - 大熊猫每条记录最近 13 个月的平均值
- python - 具有不同参数的python中的函数调度
- python - 使用 Python 3.5 在 Flask 中创建异步函数?
- java - Rest API 不能返回由其他对象组成的对象的 ArrayList
- java - 如何将 contentRoot 添加到 build.gradle
- ios - 检测何时快速按下文本字段