11

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

Community
  • 1
  • 1
Arian
  • 12,793
  • 66
  • 176
  • 300

1 Answers1

19
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.

Andrei
  • 55,890
  • 9
  • 87
  • 108