2
votes

I have a method

 private static Dictionary<string, string> getRelationPropertyAttribute(Type type)

    {
        var dicRelation = new Dictionary<string, string>();

        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            var attributes = property.GetCustomAttributes(inherit: false);

            var customAttributes = attributes
                .AsEnumerable()
                .Where(a => a.GetType() == typeof(MongoDBFieldAttribute));

            if (customAttributes.Count() <= 0)
                continue;

            for each (var attribute in custom attributes)
            {
                if (attribute is MongoDBFieldAttribute attr)
                    dicRelation[attr.Field] = property.Name;
            }
        }

        return dicRelation;
    }

In this typeof(MongoDBFieldAttribute) is getting me CustomAttributes list of all properties with MOngoDBFieldAttribute type only and I have properties as :

    [FieldIdentifier("SSI")]
    [MongoDBField("Sender State ID")]
    public string SenderStateID { get; set; }


    [FieldIdentifier("SPH")]
    [MongoDBField("Sender Phone")]
    public string SenderPhone { get; set; }

How can I make the method generic so as to get Dictionary of MongoDBField or FieldIdentifier based on need?

1
You can't make it generic, every attribute can have different properties insideMarco Salerno

1 Answers

3
votes

There's already an (extension) method GetCustomAttributes<T>()

So you can write:

using System.Reflection;

var customAttributes = property.GetCustomAttributes<MongoDBFieldAttribute>();

foreach (var attribute in customAttributes)
{
    dicRelation[attr.Field] = property.Name;
}

To make your method generic over the type of attribute, and return a dictionary where the keys are the attributes:

private static Dictionary<T, string> getRelationPropertyAttribute<T>(Type type) where T : Attribute
{
    var dicRelation = new Dictionary<T, string>();

    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        var customAttributes = property.GetCustomAttributes<T>();
        foreach (var attribute in customAttributes)
        {
            dicRelation[attr] = property.Name;
        }
    }

    return dicRelation;
}

Or you can use Linq to make it a bit terser:

private static Dictionary<T, string> getRelationPropertyAttribute<T>(Type type) where T : Attribute
{
    var pairs = from property in type.GetProperties()
                from attribute in property.GetCustomAttributes<T>()
                select new KeyValuePair<T, string>(attribute, property.Name);
    return new Dictionary<T, string>(pairs);
}