我如何排序基于自定义属性的泛型列表? [英] How do I sort a generic list based on a custom attribute?

查看:151
本文介绍了我如何排序基于自定义属性的泛型列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作在C#.NET 2.0。我有一个类,让我们说X具有许多特性。每个属性都有一个自定义属性,一个整数,我计划用指定其为了诠释他最后一个数组。

I am working in c#.NEt 2.0. I have a class, let's say X with many properties. Each properties has a custom attribute, an interger, which I planned to use to specify its order int he final array.

使用反射我从头到尾读一遍所有的属性和组的值,并把它们放入属性的泛型列表。这工作,我可以抓住的值。但是,该计划是对列表进行排序的基础上,放置在每一个属性的自定义属性,最后读出的属性格式值,已经下令,成一个字符串。

Using reflection I read through all of the properties and group the values and place them into a generic list of properties. This works and I can grab the values. But the plan was SORT the list, based on the custom attribute placed on each property, and finally read out the propery values, already ordered, into a string.

推荐答案

假设你有以下的属性定义

Lets say you had the following attribute definition

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

您可以使用下面的code拉出性能上有序类型。假设当然,他们都有这个属性。

You could use the following code to pull out the properties on a type in sorted order. Assuming of course they all have this attribute

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样式的解决方案

LINQ Style Solution

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

这篇关于我如何排序基于自定义属性的泛型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆