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[]
. My first attempt failed:
void Do(object value)
{
if (value.GetType().IsArray)
{
object[] array = (object[])value;
string[] strings = Array.ConvertAll(array, item => item.ToString());
// ...
}
}
with the runtime error Unable to cast object of type 'System.Int32[]' to type 'System.Object[]'
, which makes sense in retrospect since my int[]
doesn't contain boxed integers.
After poking around I arrived at this working version:
void Do(object value)
{
if (value.GetType().IsArray)
{
object[] array = ((Array)value).Cast<object>().ToArray();
string[] strings = Array.ConvertAll(array, item => item.ToString());
// ...
}
}
I guess this is OK, but it seems pretty convoluted. Anyone have a simpler way?
Use the Object. values() method to convert an object to an array of objects, e.g. const arr = Object. values(obj) .
A Java object is a member (also called an instance) of a Java class. Each object has an identity, a behavior and a state. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created at runtime from templates, which are also known as classes.
The first step in converting an object to another is defining a function. Mentioned earlier, a function will accept a type of GoogleLocation and will return an instance of MyLocation . Inside this method we will create a new object of MyLocation and set the values passed from GoogleGeoLocation .
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With