gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:24:56 24 4
gpt4 key购买 nike

我正在使用 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;
}

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

关于c# - 如何根据自定义属性对通用列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2231797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com