首页 > 解决方案 > 如何用枚举过滤布尔字段?

问题描述

我有一个 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; }

所以我唯一想要的是:

但是如何做到这一点?

标签: c#asp.net-core

解决方案


使用以下代码段,您可以根据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();           
}

推荐阅读