Casting entire array of objects to string
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 in开发者_开发技巧clude that into your solution. Thanks.
string[] output = Array.ConvertAll(objects, item => item.ToString());
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());
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()
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.
object[] objects;
..
string[] result = Array.ConvertAll(objects,
new Converter<object, string>(Obj2string));
public static string Obj2string(object obj)
{
return obj.ToString();
}
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();
object[] data = new object[] { "hello", "world", 1, 2 };
string[] strings = data.Select(o => o == null ? null : o.ToString()).ToArray();
Crazy question update there...
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.
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();
精彩评论