4

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?

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

2

If you don't want to use dynamic you can write your own implementation of ToDictionary method with use of Reflection. Something like this :

public static class Helper
{
    public static Dictionary<T1, T2> ToDictionary<T1, T2>(this IEnumerable<object> dict, string key, string value)
    {
        Dictionary<T1, T2> meowDict = new Dictionary<T1, T2>();

        foreach (object item in dict)
            meowDict.Add((T1)item.GetType().GetProperty(key).GetValue(item),
                (T2)item.GetType().GetProperty(value).GetValue(item));

        return meowDict;
    }
}

Usage example :

        object[] internationalRates = new object[] 
        { 
            new { name = "London", value = 1 }, 
            new { name = "New York", value = 2 } , 
        };

        var dict = internationalRates.ToDictionary<int, string>("value", "name");

        foreach (KeyValuePair<int, string> item in dict)
            Console.WriteLine(item.Key + "  " + item.Value);

        Console.ReadLine();

Output :

1 London

2 New York

Comments

1

Change your definition to this:

var internationalRates = new [] 
{ 
    new { name = "London", value = 1 }, 
    new { name = "New York", value = 2 } , 
};

And then you can use this:

var res = internationalRates.ToDictionary(x => x.value, x => x.name);

1 Comment

I can't change definition, because I need to work with such array. Definition in question was just an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.