问题
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.
回答1:
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()
回答2:
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());
回答3:
string[] output = Array.ConvertAll(objects, item => item.ToString());
回答4:
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.
回答5:
object[] objects;
..
string[] result = Array.ConvertAll(objects,
new Converter<object, string>(Obj2string));
public static string Obj2string(object obj)
{
return obj.ToString();
}
回答6:
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();
回答7:
object[] data = new object[] { "hello", "world", 1, 2 };
string[] strings = data.Select(o => o == null ? null : o.ToString()).ToArray();
Crazy question update there...
回答8:
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.
回答9:
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();
来源:https://stackoverflow.com/questions/3394703/casting-entire-array-of-objects-to-string