【问题标题】:How do I sort a generic list based on a custom attribute?如何根据自定义属性对通用列表进行排序?
【发布时间】:2010-02-09 19:19:05
【问题描述】:

我正在使用 c#.NEt 2.0。我有一堂课,假设 X 有很多属性。每个属性都有一个自定义属性,一个整数,我计划用它来指定它在最终数组中的顺序。

使用反射,我阅读了所有属性并将值分组并将它们放入一个通用的属性列表中。这行得通,我可以抓住价值。但计划是对列表进行排序,根据放置在每个属性上的自定义属性,最后将已经排序的属性值读出到一个字符串中。

【问题讨论】:

    标签: c# .net generics reflection attributes


    【解决方案1】:

    假设您有以下属性定义

    public class SortAttribute : Attribute { 
      public int Order { get; set; }
      public SortAttribute(int order) { Order = order; }
    }
    

    您可以使用以下代码按排序顺序提取类型的属性。当然假设他们都有这个属性

    public IEnumerable<object> GetPropertiesSorted(object obj) {
      Type type = obj.GetType();
      List<KeyValuePair<object,int>> list = new List<KeyValuePair<object,int>>();
      foreach ( PropertyInfo info in type.GetProperties()) {
        object value = info.GetValue(obj,null);
        SortAttribute sort = (SortAttribute)Attribute.GetCustomAttribute(x, typeof(SortAttribute), false);
        list.Add(new KeyValuePair<object,int>(value,sort.Order));
      }
      list.Sort(delegate (KeyValuePair<object,int> left, KeyValuePair<object,int> right) { left.Value.CompareTo right.Value; });
      List<object> retList = new List<object>();
      foreach ( var item in list ) {
        retList.Add(item.Key);
      }
      return retList;
    }
    

    LINQ 风格解决方案

    public IEnumerable<string> GetPropertiesSorted(object obj) {
      var type = obj.GetType();
      return type
        .GetProperties()
        .Select(x => new { 
          Value = x.GetValue(obj,null),
          Attribute = (SortAttribute)Attribute.GetCustomAttribute(x, typeof(SortAttribute), false) })
        .OrderBy(x => x.Attribute.Order)
        .Select(x => x.Value)
        .Cast<string>();
    }
    

    【讨论】:

    • 您的答案适用于 C#3+ 和 linq,但在 framework 2.0 中不可用
    • 如果我只想获取具有排序属性的属性?代码不是缺少对没有两个具有相同顺序的属性的验证吗?
    猜你喜欢
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 2021-09-10
    • 2019-06-30
    • 1970-01-01
    • 2022-01-11
    • 2021-06-27
    相关资源
    最近更新 更多