title: Linq Reflection Query to Lookup an Object's Property Name by Attribute
body: <p>I need a linq query that looks up the property name of an object based on the XmlElementAttribute having a name value of "Foo" FIRST and if not, then just give the name of the property. So the query would return a single string of the property name or null neither of these criteria exist.</p>
  
  <p>Example:</p>
  
  <pre><code>public class MyClass
  {
     [XmlElement("Foo")]
     public int MyInt {get; set;}
     [XmlElement("FooString")]
     public string MyString {get; set;}
  }
  </code></pre>
  
  <p>So if I wanted to find "MyInt" but I am given "Foo", the query would first see if it finds a property with an XmlElementAttribute with a name of "Foo". If not, then just match on the property names to find "MyInt". If "MyInt" can not be found, the value would be null.</p>
  
  <p>Here is what I have so far (it's not correct):</p>
  
  <pre><code>var propertyName = targetObject.GetType().GetProperties()
     .Select(property =&gt; new {property, attributes = property.GetCustomAttributes(true)})
     .Where(@t =&gt; @t.attributes.Any())
     .SelectMany(@t =&gt; @t.attributes, (@t, attribute) =&gt; new {@t, attribute})
     .Where(@t =&gt; @t.attribute.GetType() == typeof(XmlElementAttribute))
     .Select(@t =&gt; @t);
  </code></pre>
  
  <p>Obviously cleaner implementations are welcome.</p>