dimanche 12 avril 2020

C# Find Object's Properties that match a certain criteria

Assume for a moment you have this class:

// this is c# btw

class Rewards {

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

and you created an Instance of that class somewhere and updated some of it's values

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

Now, what you wanna do is get the Name of the properties whose values match a certain criteria (For example: A property where the value is bigger than 0 -> in this case Property1 would be returned / pushed into array

How would you go about that?

My Attempt:

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

So what it should do is iterate over each property, run a certain criteria, and store that property in a list if it passed the test

I get it I can iterate over the list with a for loop, but I want a solution with a Where query





Aucun commentaire:

Enregistrer un commentaire