I have an object
whose value may be one of several array types like int[]
or string[]
, and I want to convert it to a string[]
void Do(object value)
{
if (value.GetType().IsArray)
{
string[] strings = ((object[]) value).Select(obj => Convert.ToString(obj)).ToArray();
}
}
.ToArray
makes multiple memory allocations in most cases, but there are few ways around it:
object value = new[] { 1, 2.3 };
IList list = value as IList;
string[] strings = new string[list.Count];
for (int i = 0; i < strings.Length; i++)
strings[i] = Convert.ToString(list[i]);
In most cases that might be a bit overkill and waste of vertical space, so I would use something like the accepted answer with an optional null-conditional operator ? to check if the source is array:
string[] strings = (value as Array)?.Cast<object>().Select(Convert.ToString).ToArray();
You don't need to convert it to an array and then use LINQ. You can do it in a more streaming fashion, only converting to an array at the end:
var strings = ((IEnumerable) value).Cast<object>()
.Select(x => x == null ? x : x.ToString())
.ToArray();
(Note that this will preserve nulls, rather than throwing an exception. It's also fine for any IEnumerable
, not just arrays.)
The solution below is in JAVA
public static Objects[] convertObjectToObjectArray(){
Objects firstObject = new Object();
return new Object[]{firstObject};
}
In the above return statement, you are converting an object to an object array.