c# - 按其属性的属性值对 PropertyInfos 列表进行排序

标签 c# linq properties attributes

我有一个 Dto 类型的对象:

public class ClassA
{       
    [DataMember(Order = 10)]
    public string Code { get; set; }

    [DataMember(Order = 20)]
    public string Symbology { get; set; }

    [DataMember(Order = 30)]
    public string Category { get; set; }

    public string NonMemberPropertyA { get; set; }
}

我有兴趣获取所有 DataMember 装饰属性:

 var propertyInfos = type.GetProperties().Where(p => Attribute.IsDefined(p, typeof (DataMemberAttribute)));

现在我需要根据 DataMember 属性的 Order 属性对 propertyInfos 进行排序。因为有些可能会出现故障。

所以我尝试添加:

.OrderBy(p => ((DataFormat)Attribute.GetCustomAttribute(p, typeof (DataFormat))).Order);

但我收到“无法从使用情况推断”错误。

最佳答案

使用这个就可以了:

var orders = a1
    .GetType()
    .GetProperties()
    .Where(x => Attribute.IsDefined(x, typeof(DataMemberAttribute)))
    .Select(x => new { Att = x.GetCustomAttribute<DataMemberAttribute>(true), Prop = x })
    .OrderBy(x => x.Att.Order);

Select() 投影一个由属性本身和属性组成的匿名对象,以便您可以按属性进行排序。

a1 是对象 ClassA

的实例

我修改了你的代码并使其正常工作:

var orders = a1
    .GetType()
    .GetProperties()
    .Where(p => Attribute.IsDefined(p, typeof(DataMemberAttribute)))
    .OrderBy(p => ((DataMemberAttribute)Attribute.GetCustomAttribute(p, typeof(DataMemberAttribute))).Order);

关于c# - 按其属性的属性值对 PropertyInfos 列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33526422/

相关文章:

c# - 从csv导入到asp.net中的mysql数据库中删除双引号("")

c# - 我想从用户那里获取请求的整数数量并将它们存储到一个数组中

c# - 在 Expression<TDelegate> 中为 TDelegate 注入(inject)参数值并减少表达式

Python @property 设计

javascript - 将一个函数指定为另一个函数的属性

java - 如何读取键名中带有 ":"冒号的属性

c# - 这个按小时平均和分组的 LINQ 查询编写得是否高效?

c# - 根据权限设置默认安装目录

c# - Linq 表达式中的条件

c# - 如何使用 Entity Framework 将二进制图像从数据库加载到asp.net(无MVC)中的imagebox.imageurl