Home > Back-end >  How can I create list of nested classes where a certain property of each nested class is true?
How can I create list of nested classes where a certain property of each nested class is true?

Time:11-20

If I have a Model with nested models inside. How can I set the name property based on the NotificationModel and return a list, which is based on properties within the nested model?

I presume using Linq and Reflection.

So I have something like like: (Assume the alarms are initialised and whether they are enabled or not from a database).

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; }
}

I have had a bit of a go at reflection, but haven't found an example like mine. I haven't posted as I think it will confuse the issue. If this isn't the right approach, then please say so.

CodePudding user response:

If i understood your requirement correctly you want to filter that property NotificationModel in GetAlarmModels. Then you can use following approach:

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;
}
  • Related