How to Get a List of Properties with a Given Attribute

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

Get All properties that has a custom attribute with specific values

List<PropertyInfo> result =
typeof(ClassWithCustomAttributecs)
.GetProperties()
.Where(
p =>
p.GetCustomAttributes(typeof(UseInReporte), true)
.Where(ca => ((UseInReporte)ca).Use)
.Any()
)
.ToList();

Of course typeof(ClassWithCustomAttributecs) should be replaced with an actual object you are dealing with.

Get all properties which marked certain attribute

It's probably easiest to use IsDefined:

var properties = type.GetProperties()
.Where(prop => prop.IsDefined(typeof(LocalizedDisplayNameAttribute), false));

To get the values themselves, you'd use:

var attributes = (LocalizedDisplayNameAttribute[]) 
prop.GetCustomAttributes(typeof(LocalizedDisplayNameAttribute), false);

Reflection - Get all properties values which marked certain attribute

Not shure what result you are trying to get but this should help:

        RspServer server = new RspServer();

Type ClassType = server.GetType();

Dictionary<string, string> Description2Value = new Dictionary<string, string>();

foreach (PropertyInfo pi in ClassType.GetProperties().Where(pi => Attribute.IsDefined(pi, typeof(Description))))
{
Description d = (Description)pi.GetCustomAttributes(typeof(Description), false)[0];
string PropVal = (string)pi.GetValue(server);

Description2Value.Add(d.Value, PropVal);
}

Retrieve properties with given attribute from different assembly

So, you're trying to filter a list of properties, and retrieve only those who declare a specific attribute? If you know the attribute's type at compile time, you can replace that whole block with this:

Type attrType = typeof (SerializableAttribute);
properties.Where(p => p.IsDefined(attrType));

If you really need to identify the attribute's type by name, then use this instead:

properties.Where(p => p.CustomAttributes.Any(
attr => attr.AttributeType.Name == "SomeAttribute"));

Edit

Replying to the second part of your question:
you are overcomplicating things. In order to get the Type object from an assembly, all you need is this:

var attributeType = entryAssembly.GetTypes()
.FirstOrDefault(t => t.Name == "SomeAttribute");

if (attributeType != null)
{
//the assembly contains the type
}
else
{
//type was not found
}

You don't have to (read: should not) retrieve the assembly name, type name, namespace and then concatenate everything.

But is there any point in retrieving the Type object? You're still using a string to retrieve a type, which is hard to maintain and easy to break. Have you thought of other possibilities?

If you have any more questions, please post them as a separate question.

Get list of properties from List of objects

LINQ is the answer. You can use it to "project" from your object collection to another collection - in this case a collection of object property values.

List<string> properties = objectList.Select(o => o.StringProperty).ToList();

list all properties with [XmlAttribute] of given class

Is it possible that you used System.Xml.XmlAttribute instead of System.Xml.Serialization.XmlAttributeAttribute?

System.Xml.XmlAttribute is used to represent an attribute from the xml document.
System.Xml.Serialization.XmlAttributeAttribute specifies that the XmlSerializer must serialize the class member as an XML attribute.

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

List object properties that have an attribute applied

You will have to use reflection (so pretty much as you suspected):

var props = typeof(Report).GetProperties()
.Where(p => p.GetCustomAttributes(typeof(Reportable), false)
.Any());

foreach (var prop in props)
{
Console.WriteLine(prop.Name);
}

Create properties in class from list / attribute in __init__

If you really want to dynamically create functions and make them members of your class instances, you can use lambda:

CHANNELS = {"T0": 0, "Tend": 1, "A": 2, "B": 3, "C" : 4, "D" : 5,
"E" : 6, "F" : 7, "G" : 8, "H" : 9}

class Foo(object):
def __init__(self):
for x in CHANNELS:
setattr(self, "read{}".format(x), lambda x=x: self.read(CHANNELS[x]))

def read(self, channel):
return self._query("REQUEST STRING {}".format(channel))

def _query(self, q):
print "query {}".format(q)

f = Foo()
f.readT0()
f.readTend()
f.readA()
f.readB()
f.readC()

It works but there are a few drawbacks:

  • it creates the same set of functions for each and any instance (for no reason in this case since all instances are based on the same CHANNELS definition)
  • these functions are not documented and won't appear in dir(Foo) or help(Foo)

jonsharpe's __getattr__ solution solves the first point but not the second. The simplest solution here is to use a class decorator that will add the getters (either as methods or properties, it's up to you) on the class itself, ie (properties version):

def with_channel_props(cls):
for x in cls.CHANNELS:
getter = lambda self, x=x: self.read(self.CHANNELS[x])
setattr(cls, "{}".format(x), property(getter))
return cls

@with_channel_props
class Baaz(object):
CHANNELS = {
"T0": 0, "Tend": 1, "A": 2, "B": 3, "C" : 4, "D" : 5,
"E" : 6, "F" : 7, "G" : 8, "H" : 9
}

def read(self, channel):
return self._query("REQUEST STRING {}".format(channel))

def _query(self, q):
return "query {}".format(q)

b = Baaz()
print b.T0
print b.Tend
print b.A
print b.B
print b.C

Now you can use dir(Baaz) and help(Baaz) or any other introspection mechanism.



Related Topics



Leave a reply



Submit