C # 4.0 get class properties with (specified attribute and .data attribute)

I would like to get which properties of my class have an exact attribute with a specific string. I have this implementation (Attribute and class):

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class IsDbMandatory : System.Attribute { public readonly string tableField; public IsDbMandatory (string tableField) { this.tableField= TableField; } } public Class MyClass { [IsDbMandatory("ID")] public int MyID { get; set; } } 

Then I get a property with a specific attribute as follows:

 public class MyService { public bool MyMethod(Type theType, string myAttributeValue) { PropertyInfo props = theType.GetProperties(). Where(prop => Attribute.IsDefined(prop, typeof(IsDbMandatory))); } } 

But I only need properties with a specific attribute isDbMandatory AND a specific string myAttributeValue inside.

How can i do this?

+4
source share
1 answer
 var props = theType .GetProperties() .Where( prop => ((IsDbMandatory[])prop .GetCustomAttributes(typeof(IsDbMandatory), false)) .Any(att => att.tableField == "blabla") ); 
+7
source

Source: https://habr.com/ru/post/1347070/


All Articles