3

I'm looking for a way to select properties that have specific custom attributes with particular values in a single LINQ Statement.

I got the properties that have the attribute that I want, but I have no clue how to select its particular value.

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

[Solution]

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 };
2
  • Isn't the code for the first class, PropertyIsMailHeaderParamAttribute in VB.NET?
    – Wai Ha Lee
    Sep 28, 2015 at 7:53
  • Yea, our library is written in VB.NET which is where I get the CustomAttribute from. Don't ask why .. mistakes were made. I also changed the Names of the classes a bit in case you guys are wondering.
    – OhSnap
    Sep 28, 2015 at 8:41

1 Answer 1

8

You either have to cast the Attribute object (using a regular cast or by e.g. using the OfType<> extension) to your type, but the easiest way would be to use the generic version of 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;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.