I have the following declared:
List<Object> misObjetos = new List<Object>();
misObjetos.Add( new { precio = 1500 , nombre = "Ciclomotor" } );
misObjetos.Add( new { precio = 300 , nombre = "Patinete" } );
How do I access, for example, the price of the second element of the list?
I have tried misObjetos[1].precio
but it doesn't work.
Simply do not define the type of the variable because you do not know it, use
var
instead and an array that you can then return toList<T>
using.ToList()
and you also have to initialize them together with the variable declaration:Another option could be using tuples:
Either way you can access
misObjetos[1].precio
You have two alternatives, personally I prefer to use dynamic, which basically tells the compiler that the data type of the variable is resolved in execution mode
The second option is to create a new list with the first record so that the compiler knows the structure of the anonymous type. Based on the answer from https://stackoverflow.com/questions/1203522/how-to-access-property-of-anonymous-type-in-c which is basically the same case
If you are going to handle objects with the same structure you can always declare a class beforehand:
And you indicate that the list you will use contains that type of object: