Search code examples
c#propertiesattributes

Get property name by attribute and its value


So I'm working on a project in C# to get the property name by attribute and its value. I have a collection:

ObservableCollection<Entity> collection = new ObsevableCollection<Entity>();
collection.Add(new Entity { Id = 5, Description = "Pizza" });
collection.Add(new Entity { Id = 2, Description = "Coca cola" });
collection.Add(new Entity { Id = 1, Description = "Broccoli" });

and the entity consists of:

class Entity
{
    public int Id { get; set; }

    [MyAttribute]
    public string Description { get; set; }

    // other properties
}

My question is: is it possible to get the specific property within the entity that has the attribute MyAttribute and also its value. This would all be from the objects from collection.


Solution

  • Use GetCustomAttributes to find the attributes, and LINQ to filter and get an anonymous object which holds the Property and the Attribute.

    Use PropertyInfo.GetValue to read the actual value.

    But please beware that the reflection calls are pretty expensive:

    var propertiesWithAttribute = typeof(Entity).GetProperties()
        // use projection to get properties with their attributes - 
        .Select(pi => new { Property = pi, Attribute = pi.GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault() as MyAttribute})
        // filter only properties with attributes
        .Where(x => x.Attribute != null)
        .ToList();
    
    foreach (Entity entity in collection)
    {
        foreach (var pa in propertiesWithAttribute)
        {
            object value = pa.Property.GetValue(entity, null);
            Console.WriteLine($"PropertyName: {pa.Property.Name}, PropertyValue: {value}, AttributeName: {pa.Attribute.GetType().Name}");
        }
    }