Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get All properties that has a custom attribute with specific values [duplicate]

Possible Duplicate:
How to get a list of properties with a given attribute?

I have a custom class like this

public class ClassWithCustomAttributecs
{
    [UseInReporte(Use=true)]
    public int F1 { get; set; }

    public string F2 { get; set; }

    public bool F3 { get; set; }

    public string F4 { get; set; }
}

I have a custom attribute UseInReporte:

[System.AttributeUsage(System.AttributeTargets.Property ,AllowMultiple = true)]
public class UseInReporte : System.Attribute
{
    public bool Use;

    public UseInReporte()
    {
        Use = false;
    }
}

No I want to get All properties that has [UseInReporte(Use=true)] how I can do this using reflection?

thanks

like image 701
Arian Avatar asked Oct 29 '12 12:10

Arian


1 Answers

List<PropertyInfo> result =
    typeof(ClassWithCustomAttributecs)
    .GetProperties()
    .Where(
        p =>
            p.GetCustomAttributes(typeof(UseInReporte), true)
            .Where(ca => ((UseInReporte)ca).Use)
            .Any()
        )
    .ToList();

Of course typeof(ClassWithCustomAttributecs) should be replaced with an actual object you are dealing with.

like image 200
Andrei Avatar answered Sep 24 '22 22:09

Andrei