How can I reflect a property that has a DataMember with a given name (let each DataMember have a unique name)? For example, in the following code, a property with DataMember that has the name "p1" is PropertyOne:
[DataContract(Name = "MyContract")]
public class MyContract
{
[DataMember(Name = "p1")]
public string PropertyOne { get; set; }
[DataMember(Name = "p2")]
public string PropertyTwo { get; set; }
[DataMember(Name = "p3")]
public string PropertyThree { get; set; }
}
I currently have:
string dataMemberName = ...;
var dataMemberProperties = typeof(T).GetProperties().Where(p => p.GetCustomAttributes(typeof(DataMemberAttribute), false).Any());
var propInfo = dataMemberProperties.Where(p => ((DataMemberAttribute)p.GetCustomAttributes(typeof(DataMemberAttribute), false).First()).Name == dataMemberName).FirstOrDefault();
It works, but it seems that it can be improved. I especially don't like what GetCustomAttributes()gets called twice.
How can I rewrite it better? Ideally, it would be great if I could make it simple single-line.
source
share