I have an array of such object
:
object[] internationalRates = new object[]
{
new { name = "London", value = 1 },
new { name = "New York", value = 2 } ,
etc...
};
I need to get List<string>
of countries (or Dictionary<int, string>
of pairs). How can I cast it?
You can use the dynamic
keyword in this case:
var result = internationalRates.ToDictionary(
x => ((dynamic)x).value,
x => ((dynamic)x).name);
This produces a Dictionary with key/value pairs.
Warning:
The key and value are both of type dynamic
, which I sorta don't like. It could potentially lead to run-time exceptions if you don't pay attention to the original types.
For example, this works fine:
string name = result[2]; // name == "New York"
This will also compile just fine, but will throw a run-time exception:
int name = result[2]; // tries to convert string to int, doesn't work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With