C# 如何根据自定义属性对常规列表进行排序?

C# 如何根据自定义属性对常规列表进行排序?,c#,.net,generics,reflection,attributes,C#,.net,Generics,Reflection,Attributes,我在c#NEt 2.0中工作。我有一个类,假设X有很多属性。每个属性都有一个自定义属性,一个整数,我计划用它来指定它在最终数组中的顺序 使用反射,我通读了所有属性,并将值分组,然后将它们放入一个通用属性列表中。这是有效的,我可以抓住这些值。但计划是根据每个属性上的自定义属性对列表进行排序,最后将已排序的属性值读入字符串 public class SortAttribute : Attribute { public int Order { get; set; } public SortA

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


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

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;
}
public IEnumerable GetPropertiesSorted(对象对象对象){
Type Type=obj.GetType();
列表=新列表();
foreach(type.GetProperties()中的PropertyInfo信息){
object value=info.GetValue(obj,null);
SortAttribute排序=(SortAttribute)属性。GetCustomAttribute(x,typeof(SortAttribute),false);
添加(新的KeyValuePair(value,sort.Order));
}
排序(委托(KeyValuePair left,KeyValuePair right){left.Value.CompareTo right.Value;});
List retList=新列表();
foreach(列表中的变量项){
retList.Add(item.Key);
}
返回列表;
}
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>();
}
public IEnumerable GetPropertiesSorted(对象对象对象){
var type=obj.GetType();
返回类型
.GetProperties()
.Select(x=>new{
Value=x.GetValue(obj,null),
Attribute=(SortAttribute)Attribute.GetCustomAttribute(x,typeof(SortAttribute),false)}
.OrderBy(x=>x.Attribute.Order)
.选择(x=>x.Value)
.Cast();
}

您的答案适用于C#3+,如果我只想获取具有排序属性的属性,那么linq wich在framework 2.0中不可用?代码没有验证两个属性的顺序是否相同吗?