首页 > 解决方案 > C# 查找符合特定条件的对象的属性

问题描述

假设你有这个类:

// this is c# btw

class Rewards {

  public int property1 {get;set;}
  public int property2 {get;set;}
  public int property3 {get;set;}
}

你在某处创建了该类的一个实例并更新了它的一些值

Rewards reward = new Rewards();
reward.property1 = 10000000000;

现在,您要做的是获取其值与特定条件匹配的属性的名称(例如:值大于 0 的属性 -> 在这种情况下Property1将被返回/推入数组

你会怎么做呢?

我的尝试:

var allRewards = typeof(Rewards).GetProperties().ToList(); // this gets all the properties, but I'm not sure how the filter them with a Where query

Debug.Log(typeof(Rewards).GetProperty(allRewards[1].Name).GetValue(rewards))); // printing one of the values as a test - which works

所以它应该做的是迭代每个属性,运行某个标准,如果它通过测试,则将该属性存储在一个列表中

我明白了,我可以使用 for 循环遍历列表,但我想要一个带有 Where 查询的解决方案

标签: c#linqclassreflectionproperties

解决方案


您可以通过获取所有属性GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)并用于Where将特定属性存储在records

List<PropertyInfo> records = rewards.GetType()
     .GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance)
     .Where(a => a.PropertyType == typeof(int) && ((int)a.GetValue(rewards)) > 10000)
     .ToList();
foreach (var item in records)
{
    Console.WriteLine(item.Name + " " + item.GetValue(rewards));
}


推荐阅读