【问题标题】:Sort according to a custom attribute根据自定义属性排序
【发布时间】:2018-09-04 07:32:21
【问题描述】:

请考虑以下代码:

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

我想为所有具有CustomAttributes.GridColumn 的属性获取字典,并按GridColumn 属性中的数字和它们的类型对它们进行排序,如下所示:

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

我该怎么做?

谢谢

【问题讨论】:

    标签: c# linq data-annotations c#-7.0


    【解决方案1】:

    这样的事情应该可以工作:

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

    它首先获取所有公共属性,创建一个包含属性和属性的对象,过滤列表以仅包含属性存在的属性,按属性索引排序,最后将其转换为字典。

    我假设属性的定义类似于:

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

    附: GetCustomAttribute&lt;T&gt;()System.Reflection.CustomAttributeExtensions 中的扩展方法,因此请确保包含 using System.Reflection;

    Try it online

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多