-1

I have this Model:

public class MobileKeyViewData
{
    [Step(StepName="PersonalData")]
    public int PhoneNumber { get; set; }

    [Step(StepName="PersonalData")]
    public string Email { get; set; }

     [Step(StepName="Confirmation")]
    public int Code{ get; set; }
}

I create StepAttribute to use as property Attribute

public class StepAttribute : Attribute
{
    private string stepName;

    public string StepName
    {
        get { return stepName; }
        set { stepName = value; }
    }
}

I Have generic class to get a IEnumerable properties passing the "" a class Attribute, instance is the Object Model and the property name.

public static IEnumerable<PropertyInfo> GetPropertiesFrom<T>(this object instance,string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var properties = instance.GetType()
        .GetProperties()
        .Where (x =>
        );

    //return (T)property.GetCustomAttributes(attrType, false).First();
    //typeof(DisplayAttribute), true) //select many because can have multiple attributes
    //        .Select(e => ((DisplayAttribute)e))) //change type from generic attribute to DisplayAttribute
    //    .Where(x => x != null).Select(x => x.Name)
    return properties;
}

Question: How return a IEnumerable PropertyInfo from a Model Where StepAtttribute.StepName is equal propertyName?

Fabio Santos
  • 253
  • 1
  • 4
  • 15

1 Answers1

1

It's not 100% clear what you are asking, but from your question, it appears you want a method that will take a class of any type and a string for "name" and use those to get a list of properties on the given class where the name is set to the given name. Does the following help you?:

private static IEnumerable<PropertyInfo> GetPropertiesByStepName<TModel>(TModel model, string name)
{
    // Get the properties where there is a StepAttribute and the name is set to the `name` parameter
    var properties = model.GetType()
        .GetProperties()
        .Where(x =>
            x.GetCustomAttribute<StepAttribute>() != null &&
            x.GetCustomAttribute<StepAttribute>().Name == name);

    return properties;
}

NOTE: You need to use the namespace System.Reflection

Matt
  • 6,787
  • 11
  • 65
  • 112
  • I change added the attribute Class. – Fabio Santos May 02 '18 at 09:10
  • @FabioSantos Your updated question is also confusing because you want to pass a generic type of Attribute in, which can be ANY type of attribute (not only `StepAttribute`), but then you also asked this: "How return a IEnumerable PropertyInfo from a Model Where StepAtttribute.StepName is equal propertyName?" So, you expect that the attribute will have a `StepName` property, but you want to use ANY attribute?? This doesn't make any sense. – Matt May 03 '18 at 04:37