Linq Reflection查询按属性查找对象的属性名称

时间:2014-01-22 15:51:58

标签: c# linq reflection properties attributes

我需要一个linq查询,它根据名称值为“Foo”FIRST的XmlElementAttribute查找对象的属性名称,如果没有,则只需给出属性的名称。因此查询将返回属性名称的单个字符串,或者这些条件都不存在。

示例:

public class MyClass
{
   [XmlElement("Foo")]
   public int MyInt {get; set;}
   [XmlElement("FooString")]
   public string MyString {get; set;}
}

因此,如果我想找到“MyInt”但我得到“Foo”,则查询首先会查看是否找到了一个名为“Foo”的XmlElementAttribute属性。如果没有,那么只需匹配属性名称即可找到“MyInt”。如果找不到“MyInt”,则该值将为null。

这是我到目前为止(这不正确):

var propertyName = targetObject.GetType().GetProperties()
   .Select(property => new {property, attributes = property.GetCustomAttributes(true)})
   .Where(@t => @t.attributes.Any())
   .SelectMany(@t => @t.attributes, (@t, attribute) => new {@t, attribute})
   .Where(@t => @t.attribute.GetType() == typeof(XmlElementAttribute))
   .Select(@t => @t);

显然,欢迎更清洁的实施。

1 个答案:

答案 0 :(得分:1)

我明白了。我先用嵌套的foreach循环编写它,然后Resharper为我转换它。甜!

var propertyName = (from property in targetObject.GetType().GetProperties() 
                                              let attributes = property.GetCustomAttributes(true) 
                                              where attributes.Any() 
                                              let xmlAttribute = attributes.Where(a => a.GetType() == typeof (XmlElementAttribute)).Select(a => a).FirstOrDefault() as XmlElementAttribute 
                                              where xmlAttribute != null && xmlAttribute.ElementName.EqualsIgnoreCase(salesforceXmlElement.LocalName)
                                              select property.Name).FirstOrDefault() ?? salesforceXmlElement.LocalName;
相关问题