views:

156

answers:

9

I have an array of type object which are strings.

I would like to convert them to strings

what would be the quickest way of doing so.

Eg.

I have this "object[]" and want to convert it so it is this "string[]"

UPDATE -

i think the problem is that some of the objects on the object[] are actually other objects like integers. I would need to convert them to strings first. Please include that into your solution.

thanks

A: 
string[] str = new string[myObjects.Length];
for (int i = 0; i < myObjects.Length; ++i)
    str[i] = myObjects[i].ToString();

OR:

List<string> lst = new List<string>();
foreach (object o in myObjects)
    list.Add(o.ToString());
return list.ToArray();
tdammers
Long way for a shortcut...
James
+3  A: 
string[] myStringArray = myObjectArray.Cast<string>().ToArray();

or if you are using var keyword:

var myStringArray = myObjectArray.Cast<string>();

Using Cast will not throw an exception if any of your strings are null.

James
`Cast<T>()` returns an `IEnumerable<T>`, you would have to use `ToArray()` to make this compile.
0xA3
@0xA3: Yeah I updated my post. However, it would not throw an exception if the OP is using the var keyword.
James
Note that the version with `var` compiles but creates an `IEnumerable<string>` instead of a string array.
0xA3
@0xA3: Yeah good point.
James
+11  A: 
object[] data = new object[] { "hello", "world", "!" };

string[] stringData = data.Cast<string>().ToArray();

If your object array contains mixed elements you can use the ConvertAll method of Array:

object[] data = new object[] { "hello", 1, 2, "world", "!" };

string[] stringData = Array.ConvertAll<object, string>(data, o => o.ToString());
0xA3
Why use `ConvertAll` of the `List` class when there is already one implemented for `Array`? Check my answer to see how to do it properly.
Jaroslav Jandek
+6  A: 

Probably not the most efficient way to do it...it has the benefit of working when the objects aren't necessarily strings.

string[] output = (from o in objectArray
                   select o.ToString()).ToArray()
cristobalito
Why call `ToString` when you know that the objects in the array are already strings ? You just need to cast the items to `string`. Besides, `out` is a reserved keyword ;)
Thomas Levesque
You would need to rename your variable to @out.
James
@Thomas: thanks - calling ToString() to make it usable in general. As it turns out, the OP edited his post to say that some of the elements can be non-string data types (e.g. ints), so this would still have handled that case.
cristobalito
Well, after the OP updated his question, your solution is actually the right one, so +1 ;)
Thomas Levesque
Didn't have that in mind originally - there were a few other answers, so just put the LINQ one in for completeness. I like 0xA3's answer - I don't use Cast enough
cristobalito
There is already a conversion method for arrays (`Array.ConvertAll`) - LINQ just makes it slower (eg.: not the quickest way - not for CPU and not for the programmer).
Jaroslav Jandek
`from ... select` syntax is nice and all, but `objectArray.Select(o => o.ToString()).ToArray();` is actually cleaner IMO
Peter Lillevold
@Peter, using extension methods or query comprehension syntax is just a matter of taste, the result is exactly the same... But I agree with you in that case. As soon as I need to add parenthesis, I drop the query syntax.
Thomas Levesque
@Thomas, I totally agree, should have added "in this case" to my comment :)
Peter Lillevold
Good comments there on the syntax - never really thought about it, but see where you're coming from. Will bear that in mind in future.
cristobalito
+1  A: 
 object[] objects;
 ..
 string[] result = Array.ConvertAll(objects, 
        new Converter<object, string>(Obj2string));
 public static string Obj2string(object obj)
 {
    return obj.ToString();
 }
Arseny
you can use lambda: Array.ConvertAll(objects, o => o.ToString());
onof
@onof right. Or an anonymous method in case of NET2.0
Arseny
A: 
object[] data = new object[] { "hello", "world", 1, 2 };

string[] strings = data.Select(o => o == null ? null : o.ToString()).ToArray();

Crazy question update there...

Codesleuth
A: 

You can't use Enumerable.Cast if some of the object in the array are integers, it'll throw InvalidCastException when you do this:

var list = new object[] { "1", 1 };

list.Cast<string>();

Instead, try cristobalito's answer, or the lambda syntax equivalent:

list.Select(o => o.ToString()).ToArray();
theburningmonk
+4  A: 
string[] output = Array.ConvertAll(objects, item => item.ToString());
Jaroslav Jandek
+1 for mentioning a little known method. It's also probably slightly more efficient than the LINQ approach
Thomas Levesque
A: 

Since all objects are already strings the hard cast work. A safer way might be using the following:

  private static void Conversions()
  {
     var strings = Convert(new object[] {"a", "b"});
     var strings2 = Convert(new object[] {});
  }

  private static string[] Convert(IEnumerable<object> objects)
  {
     return objects as string[] ?? new string[] {};
  }

This implementation returns always a string array, potentially empty. Client side code can be implemented based on that assumption and you avoid having to check the return value for null.

John