Search code examples
c#modeldto

c# select from model by type


I wonder if there is a way to select elements from model, based on type. Here is the model:

public class Progress : BaseModel
{
    public DateTime? LimitTime { get; set; }
    public Status Status { get; set; }
    public virtual Decision ApplicationDecision { get; set; }
    public virtual Decision ValidationDecision{ get; set; }
    public virtual Decision FinalDEcision { get; set; }

    public virtual Outcome FinalChecksOutcome { get; set; }
}

public enum Status
{
    Active,
    Rejected
    Completed
}

What I want is something like:

var decisions = user.Progress.where(x=>x.type == Decision);

so based on that, to validate if the signature(inside Decision model) is null or not.

Any help is welcome.


Solution

  • To get all Properties of a certain Type you need to use reflection. For example you could do the following:

    var decisions = typeof(Progress).GetProperties().Where(p => p.PropertyType == typeof(Decision)).ToArray();
    

    Afterwards you can loop over the properties and do whatever you need.

    If you need to inspect an object (and not the type itself) you would need to call the following If Progress is a property of the user object):

    var decisions = user.Progress.GetType().GetProperties().Where(p => p.PropertyType == typeof(Decision)).ToArray();