I have a class with the following properties:
public class Datos
{
public int ID{ get; set; }
public string Nombre { get; set; }
public int Peso { get; set; }
}
As it is a JSON
deserialized and using that class:
var modelo = JsonConvert.DeserializeObject<List<Datos>>(jsonRecibido);
To access the data of this new object, I passed it to a foreach and extracted the data by the name of the property like this:
foreach (var item in modelo)
{
var id = item.ID;
var nombre = item.Nombre;
var peso = item.Peso;
}
Here comes my doubt, how can I do that same foreach but I don't know neither the name of the property nor the value, for example something like this:
var ListaNombre=new List<string>();
var ListaValor=new List<string>();
foreach(var item in modelo)
{
ListaNombre.Add(item...Name/Propiedad); //se guarda el nombre ya sea ID, Nombre, Peso, etc
ListaValor.Add(item...Value); //aqui iria "pepe", 4, 67567, etc
}
How would you do that?
As @gbianchi comments, it is an issue that is resolved using Reflection , specifically I am going to give you a solution using
GetProperties
andGetValue
:Keep in mind that we are storing the values as
string
. It could be assigned to the specific type, but that would be a more complex issue.