【问题标题】:How can I create list of nested classes where a certain property of each nested class is true?如何创建嵌套类列表,其中每个嵌套类的某个属性为真?
【发布时间】:2021-12-30 02:33:31
【问题描述】:

如果我有一个里面有嵌套模型的模型。如何根据 NotificationModel 设置 name 属性并返回一个列表,该列表基于嵌套模型中的属性?

我假设使用 Linq 和 Reflection。

所以我有类似的东西:(假设警报已初始化以及它们是否从数据库启用)。

public class AlarmController : IAlarmController
{
    public AlarmController()
    {        
        this.NotificationModel = new NotificationModel();
    }
    
    public NotificationModel NotificationModel { get; set; }
    
    public List<AlarmModel> GetAlarmModels()
    {
     //this.NotificationModel --something... where isEnabled == true.

     return new List<AlarmModel>();
    }
}       

public class NotificationModel
{
        public AlarmModel HardwareFault{ get; set; }

        public AlarmModel TimeoutFault { get; set; }

        public AlarmModel GenericFault { get; set; }
}

public class AlarmModel
{
    public string Name { get; set; }

    public bool isActive { get; set; }

    public bool isEnabled { get; set; }

    public bool isSilenced { get; set; }
}

我曾尝试过反思,但还没有找到像我这样的例子。我没有发布,因为我认为它会混淆问题。如果这不是正确的方法,请说出来。

【问题讨论】:

    标签: c# linq class reflection


    【解决方案1】:

    如果我正确理解了您的要求,您希望在GetAlarmModels 中过滤该属性NotificationModel。然后您可以使用以下方法:

    public List<AlarmModel> GetAlarmModels() => EnabledAlarms().ToList();
    
    private IEnumerable<AlarmModel> EnabledAlarms()
    {
        if(NotificationModel.HardwareFault.isEnabled)
            yield return NotificationModel.HardwareFault;
        if(NotificationModel.TimeoutFault.isEnabled)
            yield return NotificationModel.TimeoutFault;
        if(NotificationModel.GenericFault.isEnabled)
            yield return NotificationModel.GenericFault;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      相关资源
      最近更新 更多