Select 个具有特定属性值的属性

Select properties with specific attribute value

我正在寻找一种方法来 select 在单个 LINQ 语句中具有特定自定义属性和特定值的属性。

我得到了具有我想要的属性的属性,但我不知道如何select它的特定值。

<AttributeUsage(AttributeTargets.Property)>
Public Class PropertyIsMailHeaderParamAttribute
    Inherits System.Attribute

    Public Property HeaderAttribute As String = Nothing
    Public Property Type As ParamType = Nothing

    Public Sub New()

    End Sub

    Public Sub New(ByVal headerAttribute As String, ByVal type As ParamType)
        Me.HeaderAttribute = headerAttribute
        Me.Type = type
    End Sub

    Public Enum ParamType
        base = 1
        open
        closed
    End Enum
    End Class


    private MsgData setBaseProperties(MimeMessage mailItem, string fileName)
    {
        var msgData = new MsgData();
        Type type = msgData.GetType();
        var props = from p in this.GetType().GetProperties()
                    let attr = p.GetCustomAttributes(typeof(Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute), true)
                    where attr.Length == 1
                    select new { Property = p, Attribute = attr.FirstOrDefault() as Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute };
    }

[解决方案]

var baseProps = from p in this.GetType().GetProperties()
                let attr = p.GetCustomAttribute<PropertyIsMailHeaderParamAttribute>()
                where attr != null && attr.Type == PropertyIsMailHeaderParamAttribute.ParamType.@base
select new { Property = p, Attribute = attr as Business.IT._21c.AddonFW.PropertyIsMailHeaderParamAttribute };

您必须将 Attribute 对象(使用常规转换或例如使用 OfType<> 扩展)转换为您的类型,但最简单的方法是使用通用版本GetCustomAttribute<>:

var props = from p in this.GetType().GetProperties()
            let attr = p.GetCustomAttribute<PropertyIsMailHeaderAttribute>()
            where attr != null && attr.HeaderAttribute == "FooBar"
                               && attr.Type = ParamType.open
            select whatever;