【问题标题】:Linq Reflection Query to Lookup an Object's Property Name by AttributeLinq 反射查询以按属性查找对象的属性名称
【发布时间】:2014-02-12 18:55:41
【问题描述】:

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

例子:

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

显然更干净的实现是受欢迎的。

【问题讨论】:

    标签: c# linq reflection properties attributes


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多