ferpega
ferpega

Reputation: 3224

c# 4.0 get class properties with (specified attribute and attribute.data)

I would like to get what properties of my class have an exact attribute with a concrete string. I have this implementation (Attribute and Class):

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class IsDbMandatory : System.Attribute
{
    public readonly string tableField;

    public IsDbMandatory (string tableField)
    {
        this.tableField= TableField;
    }
}

public Class MyClass 
{
    [IsDbMandatory("ID")]
    public int MyID { get; set; }
}

Then I get the property with the concrete attribute in this way:

public class MyService
{
   public bool MyMethod(Type theType, string myAttributeValue)
   {            
       PropertyInfo props = 
           theType.GetProperties().
                  Where(prop => Attribute.IsDefined(prop, typeof(IsDbMandatory))); 
   }
}

But I need only the properties with concrete attribute isDbMandatory AND concrete string myAttributeValue inside.

How can I do it ?

Upvotes: 4

Views: 2866

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

var props = theType
    .GetProperties()
    .Where(
        prop => ((IsDbMandatory[])prop
            .GetCustomAttributes(typeof(IsDbMandatory), false))
            .Any(att => att.tableField == "blabla")
    );

Upvotes: 7

Related Questions