21

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.

2
  • 4
    talk about changing the goal-posts :) Commented Aug 3, 2010 at 8:19
  • sorry! i didn't realize that was actually the problem Commented Aug 3, 2010 at 8:23

9 Answers 9

17
string[] output = Array.ConvertAll(objects, item => item.ToString());
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for mentioning a little known method. It's also probably slightly more efficient than the LINQ approach
17
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());

1 Comment

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.
13

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()

10 Comments

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 ;)
You would need to rename your variable to @out.
@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.
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).
from ... select syntax is nice and all, but objectArray.Select(o => o.ToString()).ToArray(); is actually cleaner IMO
|
3
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.

3 Comments

Cast<T>() returns an IEnumerable<T>, you would have to use ToArray() to make this compile.
@0xA3: Yeah I updated my post. However, it would not throw an exception if the OP is using the var keyword.
Note that the version with var compiles but creates an IEnumerable<string> instead of a string array.
1
 object[] objects;
 ..
 string[] result = Array.ConvertAll(objects, 
        new Converter<object, string>(Obj2string));
 public static string Obj2string(object obj)
 {
    return obj.ToString();
 }

1 Comment

you can use lambda: Array.ConvertAll(objects, o => o.ToString());
0
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();

Comments

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

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

Crazy question update there...

Comments

0

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.

Comments

0

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();

Comments

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.