Search code examples
c#linqdata-annotationsc#-7.0

Sort according to a custom attribute


Please Consider this code:

public class MyClass
{
    [CustomAttributes.GridColumn(1)]
    public string Code { get; set; }

    [CustomAttributes.GridColumn(3)]
    public string Name { get; set; }

    [CustomAttributes.GridColumn(2)]
    public DateTime? ProductionDate { get; set; }

    public DateTime? ProductionExpiredDate { get; set; }

    [CustomAttributes.GridColumn(4)]
    public int ProductOwner { get; set; }
}

I want to get a dictionary for all properties that have CustomAttributes.GridColumn and sort them by the number in GridColumn attribute and type of them like this:

PropertyName           Type
---------------------------------
Code                   string 
ProductionDate         DateTime?
Name                   string 
ProductOwner           int 

How I can do this?

Thanks


Solution

  • Something like this ought to work:

    private IDictionary<string, Type> GetProperties<T>()
    {
        var type = typeof(T);
        return type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                    .Select(p => new { Property = p, Attribute = p.GetCustomAttribute<CustomAttributes.GridColumnAttribute>() })
                    .Where(p => p.Attribute != null)
                    .OrderBy(p => p.Attribute.Index)
                    .ToDictionary(p => p.Property.Name, p => p.Property.PropertyType);
    }
    

    It first gets all of the public properties, creates an object which contains the property and the attribute, filters the list to only include properties where the attribute exists, sorts by the attribute index, and finally converts it into a dictionary.

    I'm assuming the attribute is defined similar to this:

    public class GridColumnAttribute : System.Attribute
    {
        public GridColumnAttribute(int index)
        {
            this.Index = index;
        }
    
        public int Index { get; set; }
    }
    

    P.S. GetCustomAttribute<T>() is an extension method that lives in System.Reflection.CustomAttributeExtensions so make sure you include a using System.Reflection;

    Try it online