简体   繁体   English

按名称 C# 对对象属性列表进行排序

[英]Sort an object property list by Name C#

I have an object which contains many properties of type string and whose name consists of a text and number like Property1 , Property3 , Property12 ... etc.我有一个对象,其中包含许多字符串类型的属性,其名称由文本和数字组成,如Property1Property3Property12 ...等。

I want to get a sorted list (OrderByDescending) of properties whose value is not null.我想获得其值不为空的属性的排序列表 (OrderByDescending)。

This means the property at the first position the should be the the property whose number (not the value) which is a part of name is highest.这意味着第一个位置的属性应该是作为名称的一部分的数字(而不是值)最高的属性。

For Example: In the case that the list contains objects with following properties:例如:如果列表包含具有以下属性的对象:

(Property Name: Value) (属性名称:值)

  1. Property1: 3物业1:3
  2. Property2: null属性 2:空
  3. Property3: 2物业3:2
  4. Property4: null属性 4:空

This should be the sorted list that I need:这应该是我需要的排序列表:

  1. Property3: 2物业3:2
  2. Property1: 3物业1:3

Here is what I tried but it doesn't work:这是我尝试过但不起作用的方法:

var objectType= typeof(Type);
var result = objectType.GetProperties()
    .Where(p => p.Name.Contains("Property") && p.GetValue(object) != null);
    .OrderByDescending(p => p.Name);

Please can you help me to realize it?请你能帮我实现它吗?

Thanks!谢谢!

This is how I solved my problem:这就是我解决我的问题的方法:

creating a method public int GetNumberFromName(string name) { ... } that I can then use to sort my object list like this: .OrderByDescending(p => GetNumberFromName(p.Name));创建一个方法 public int GetNumberFromName(string name) { ... } 然后我可以用它来对我的对象列表进行排序,如下所示: .OrderByDescending(p => GetNumberFromName(p.Name));

Thanks for your help!谢谢你的帮助!

You could try orderby after Where clause:您可以在 Where 子句之后尝试 orderby:

var objectType= typeof(Type);
var result = objectType.GetProperties()
    .Where(p => p.Name.Contains("Property") && p.GetValue(triangleView) != null)
    .OrderBy(c => c.Name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM