Gillardo
Gillardo

Reputation: 9818

Filter PropertyInfo by attribute enum value

I have some custom properties against each of my Models as below

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class FieldAttribute : System.Attribute
{
    private FieldFor _fieldFor;

    public FieldAttribute(FieldFor fieldFor)
    {
        _fieldFor = fieldFor;
    }
}

The type FieldFor is an enumeration. So i can declare this against a field like so

[Field(FieldFor.Name)]
public string Name { get; set; }

Now to get a list of the properties on my model that have this custom attribute, i use the following

List<PropertyInfo> props = new MyModel().GetType().GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(FieldAttribute))).ToList<PropertyInfo>();

Now i have the list of all properties that have my custom attribute, how can i get which property has a FieldFor value of Name??

I am doing both queries separately as i have to get the values for many properties on my model

Upvotes: 0

Views: 1787

Answers (2)

ken2k
ken2k

Reputation: 48975

You could do:

var props = new MyModel()
    .GetType()
    .GetProperties()
    .Where(prop =>
        {
            var fieldAttribute = prop.GetCustomAttribute<FieldAttribute>();
            if (fieldAttribute != null)
            {
                return fieldAttribute.FieldFor == FieldFor.Name;
            }

            return false;
        })
    .ToList();

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can get the attribute using GetCustomAttribute method, then you can access it's members:

foreach(var prop in props)
{
    var fieldAttribute = prop.GetCustomAttribute<FieldAttribute>();
    var value = fieldAttribute.FieldFor;
}

It would be useful to add a public property to get FieldFor's value.Right now you have only a private field.

public FieldFor FieldFor { get { return _fieldFor; } }

Using linq:

props.Where(x => x.GetCustomAttribute<FieldAttribute>().FieldFor == FieldFor.Name);

Upvotes: 2

Related Questions