简体   繁体   English

Linq反射查询以按属性查找对象的属性名称

[英]Linq Reflection Query to Lookup an Object's Property Name by Attribute

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. 我需要一个linq查询,该查询基于名称为“ Foo”的XmlElementAttribute查找对象的属性名称,如果不是,则只给出属性名称。 So the query would return a single string of the property name or null neither of these criteria exist. 因此,查询将返回属性名称的单个字符串或null,这两个条件都不存在。

Example: 例:

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

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". 因此,如果我想查找“ MyInt”,但是却得到“ Foo”,则查询将首先查看它是否找到名称为“ Foo”的XmlElementAttribute属性。 If not, then just match on the property names to find "MyInt". 如果不是,则只需在属性名称上匹配以找到“ MyInt”。 If "MyInt" can not be found, the value would be null. 如果找不到“ MyInt”,则该值为空。

Here is what I have so far (it's not correct): 这是我到目前为止的信息(不正确):

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

Obviously cleaner implementations are welcome. 显然,更清洁的实现是受欢迎的。

I figured it out. 我想到了。 I coded it out in nested foreach loops first and Resharper converted it for me. 我先在嵌套的foreach循环中将其编码,然后Resharper为我进行了转换。 Sweet! 甜!

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM