如何根据自定义属性对通用列表进行排序?

don*_*nde 5 .net c# generics reflection attributes

我在c#.NEt 2.0工作.我有一个类,让我们说X有很多属性.每个属性都有一个自定义属性,一个整数,我打算用它来指定最终数组中的顺序.

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

Jar*_*Par 11

假设您有以下属性定义

public class SortAttribute : Attribute { 
  public int Order { get; set; }
  public SortAttribute(int order) { Order = order; }
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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>();
}
Run Code Online (Sandbox Code Playgroud)

  • 你的答案适用于C#3 +,而linq在框架2.0中不可用 (2认同)