// using System.Linq;
// using System.Reflection;
// using System.Runtime.Serialization;
obj.GetType()
.GetProperties(…)
.Where(p => Attribute.IsDefined(p, typeof(DataMemberAttribute)))
.Single(p => ((DataMemberAttribute)Attribute.GetCustomAttribute(
p, typeof(DataMemberAttribute))).Name == "Foo");
Notes:
Attribute.IsDefined
is used to check for the presence of a custom attribute without retrieving its data. Thus it is more efficient thanAttribute.GetCustomAttribute
and used to skip properties in a first step.After the
Where
operator, we are left with properties that have exactly oneDataMemberAttribute
: Properties without this attribute have been filtered out, and it cannot be applied more than once. Therefore we can useAttribute.GetCustomAttribute
instead ofAttribute.GetCustomAttributes
.