Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Parse anonymous type to List of string values

Tags:

c#

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?

like image 807
Alexander Avatar asked Feb 10 '23 00:02

Alexander


1 Answers

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
like image 87
Grant Winney Avatar answered Feb 11 '23 13:02

Grant Winney