【问题标题】:Sort properties given attribute paramter order给定属性参数顺序对属性进行排序
【发布时间】:2017-01-18 04:51:43
【问题描述】:

我想根据给定的属性参数Order 对属性进行排序。

属性:

public class Items: Attribute
{
    public int Order { get; set; }
    public Items(int order)
    { 
      this.Order = order;
    }
}

实施:

public class client
{
   [Items(1)]
   public string fName {get; set;}

   [Items(3)]
   public string lName {get; set;}

   [Items(2)]
   public string mName {get; set;}
}

获取所有属性:

var properties = typeof(client).GetProperties().Where(
prop => prop.IsDefined(typeof(Items), false));

按顺序#排序?

这是我尝试过的,但它不起作用

Array.Sort(properties, delegate (Items x, Items y) 
{ return x.Order.CompareTo(y.Order); });

如何根据订单对属性进行排序?

这个问题已经解决了,但是想扩展这个问题。

Is there a way to sort properties without having to put an "Order" on them。我只想有一个属性“EndOfList”或“Last”来说明一定要对这些最后进行排序。这样我就不必用 Orders 把代码弄得乱七八糟了。

【问题讨论】:

    标签: c# sorting properties attributes


    【解决方案1】:

    你可以使用 Linq 和OrderBy

    var sorted = properties
        .OrderBy(p => ((Items)p.GetCustomAttributes(true)
                               .FirstOrDefault(a => a is Items)).Order);
    

    这会产生以下顺序:fNamemNamelName

    那么在 OrderBy 内部会发生什么:访问自定义属性。查找类型为Items 的第一个并将Order 属性用作排序参数。

    要以相反的顺序排序,只需使用OrderByDescending

    【讨论】:

      【解决方案2】:

      你可以试试这个

      var properties = typeof(client).GetProperties().Where(prop => prop.IsDefined(typeof(Items), false));
      var sortedProperties = properties.OrderBy(x =>  ((Items)x.GetCustomAttributes(typeof(Items), false).FirstOrDefault()).Order);
      

      【讨论】:

        猜你喜欢
        • 2018-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 2019-05-29
        • 2019-11-21
        相关资源
        最近更新 更多