如何对C#类中通过反射获取的属性按名称排序?
按属性名称排序反射获取的PropertyInfo数组
你可以通过LINQ的OrderBy方法,基于PropertyInfo的Name属性对数组进行排序,具体实现如下:
- 确保代码文件顶部引入
System.Linq命名空间(未引入的话需要添加):
using System.Linq;
- 修改获取属性数组的代码,在
GetProperties()后链式调用排序方法:
MyClass md = new MyClass(); // 按属性名称升序排序 PropertyInfo[] properties = typeof(MyClass) .GetProperties() .OrderBy(p => p.Name) .ToArray(); foreach (PropertyInfo property in properties) { double? d1 = /* 你的取值逻辑 */; if (property.PropertyType == typeof(double?)) { if (property.GetValue(md) == null) { property.SetValue(md, d1); } } }
如果需要按名称降序排序,只需将OrderBy替换为OrderByDescending:
PropertyInfo[] properties = typeof(MyClass) .GetProperties() .OrderByDescending(p => p.Name) .ToArray();
处理后,遍历属性时会按照属性名称的字母顺序(默认区分大小写)执行赋值操作。
内容的提问来源于stack exchange,提问作者Jassim S
相关产品推荐
相关产品推荐

