The Oddler
The Oddler

Reputation: 6708

Convert object of type List<object> to List<string>

I'm parsing a JSON string using MiniJson in Unity. Now I have a value that's a list of strings. Though I get this an object. The underlying type of the object is a List<object>, but actually it should be a List<string>. So currently I do this:

void SetInfo(Dictionary<string,object> info) {
    Colors = (info["colors"] as List<object>).OfType<string>().ToList();
}

The dictionary is what I get from the MiniJson library. This works perfectly. Though seems a bit ugly, a lot of unnecessary casting, and I was wondering if there's a better way of doing this. Mostly I'm looking for cleaner code, and faster execution, since there are a lot of these entries.

Edit: I wasn't very clear about this. In the info dictionary there are a bunch of key/value pairs, the type of the values vary. I can cast most very easily, but the info["colors"] object is the one I'm having problems with.

So when I do info["colors"] I get an object, with an underlying type List<object>. The objects in this list are actually strings.

Also, there's not really a performance problem here, since it's only called once at the start of the program, though there is a noticeable lag currently, I'm going to put it on it's own thread anyway so no problem there. The faster execution is just out of curiosity.

Upvotes: 0

Views: 3325

Answers (3)

Phillip Ngan
Phillip Ngan

Reputation: 16106

I know this code is a bit old school, but we all know what it means:

    List<object> l = new List<object>();
    List<string> s = new List<string>();
    foreach( var i in l )
        s.Add((string)i);

Upvotes: 0

Andrew
Andrew

Reputation: 144

Have you thought about using the in and out keywords

Upvotes: 0

Andrew
Andrew

Reputation: 3796

Try this one.

(info["colors"] as List<object>).ConvertAll(input => input.ToString());

you can also use direct cast (string)input or input as string which is even faster(there were debates on casting here at stackoverflow).

info["colors"] as List<object> can result in null, so I'd rather be more safe and wrap your code like this:

List<object> colors = info["colors"] as List<object>;
List<string> typedColors = null;
if (colors!=null)
{
   typedColors = colors.ConvertAll(input => input as string);
}

Upvotes: 4

Related Questions