2014-01-22 59 views
0

我需要一個linq查詢,查找基於名稱值爲「Foo」的XmlElementAttribute的對象的屬性名稱,如果不是,則只需指定名稱的財產。因此,查詢將返回屬性名稱的單個字符串,或者null都不存在這些條件。Linq反射查詢按屬性查找對象的屬性名稱

例子:

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

所以,如果我想找到「敏」,但是我給「富」,查詢會先看看,如果發現物業設有XmlElementAttribute與「富」的名字。如果不是,那麼匹配屬性名稱以找到「MyInt」。如果找不到「MyInt」,則該值爲空。

這是我迄今(這是不正確):

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); 

顯然更清潔的實現是值得歡迎的。

回答

0

我想通了。我先將它編入嵌套的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;