Shin
Shin

Reputation: 673

How to filter a class properties collection?

Example: I have this class

public class MyClass
{
    private string propHead;
    private string PropHead { get; set; }

    private int prop01;
    private int Prop01 { get; set; }

    private string prop02;
    private string Prop02 { get; set; }

    // ... some more properties here

    private string propControl;
    private string PropControl { get; }  // always readonly
}

I need to exclude propHead and propControl. To exclude propControl:

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType().GetProperties().Where(x => x.CanWrite).ToArray();

Now, how could I exclude propHead?, when all share same level of accesibility. Is there any way to add a special attribute to propHead that let me exclude it from the others. Properties names always is different in each class.

Any suggestions would be very apreciated.

Upvotes: 2

Views: 2908

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149040

This would be the easiest way:

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType()
    .GetProperties()
    .Where(x => x.Name != "propHead" && x.Name != "propControl")
    .ToArray();

But if you're looking for a more general-purpose solution, you can try this

public class CustomAttribute : Attribute
{
    ...
}

MyClass mc = new MyClass();
PropertyInfo[] allProps = mc.GetType()
    .GetProperties()
    .Where(x => x.GetCustomAttributes(typeof(CustomAttribute)).Length > 0)
    .ToArray();

Upvotes: 1

Related Questions