简体   繁体   中英

How can I create list of nested classes where a certain property of each nested class is true?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM