Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a property has a specific attribute?

Tags:

c#

I'm using WCF RIA services to do a few small pieces of a web application; mainly populate/filter lists (I don't understand RIA well enough yet to trust I'm doing server side validation correct). One of the things I do is get a list of which fields have which generic type, by which I mean, strings are a text type, decimal, double, integer are numeric, etc. I do that with a LINQ query

Fields = type.GetProperties().Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null && pi.Name != "DisplayName")
                            .Select(pi => new FieldData
                            {
                                FieldName = CommonResources.AddSpacesToSentence(pi.Name, true),
                                FieldType = "Text"
                            }).....

The field DisplayName is a special field that should be ignored in lists, but as this application is growing I realize this isn't a very maintainable/expandable/buzzwordable way to go about this. What I really want is to know is if metadata for the DisplayName property has the attribute [Display(AutoGenerateField = false)]

Is there a way I can check for that in my LINQ?

Update:

After posting this I was able to slowly work out how to do this (I've never worked with Attributes in this way before). The answer given by King King looks nice and is very generic, but the way I wound up solving this was different, so if you're interested in another way, here's what I found. I added this to the LINQ query:

((DisplayAttribute)Attribute.GetCustomAttribute(pi, typeof(DisplayAttribute))).GetAutoGenerateField() == false
like image 954
cost Avatar asked Oct 13 '25 03:10

cost


1 Answers

You can use the GetCustomAttributes method to filter properties with the given attribute:

...
.Where(pi => pi.GetCustomAttributes(typeof(DisplayAttribute), true).Any())
...

The true argument includes inheritance in attribute search.

like image 132
BartoszKP Avatar answered Oct 14 '25 17:10

BartoszKP