I have many ways to do it but still want to know is there any offical API to convert object[] to string[] With null checked? Thanks
As list. toArray() returns an Object[], it can be converted to String array by passing the String[] as parameter.
So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.
object can be anything uint[], int16[], etc. string[] str = Array. ConvertAll<object, string>((object[])obj, Convert. ToString);
You could just run a simple conversion on it using the ConvertAll method in the Array class and a lambda on the object itself.
object[] inputArray = new object[10];
string[] resultArray = Array.ConvertAll(inputArray, x => x.ToString());
If you have a method to convert an object
to a string
(or int
) with null check, then you can use the Array.ConvertAll<TInput, TOutput> Method to convert an object[]
to a string[]
(or int[]
):
object[] input = ...;
string[] result = Array.ConvertAll<object, string>(input, ConvertObjectToString);
string ConvertObjectToString(object obj)
{
return obj?.ToString() ?? string.Empty;
}
If you want to skip items in the object[]
array when converting to a string[]
, a more convenient approach might be using the extension methods of the Enumerable Class:
object[] input = ...;
string[] result = input.Where(x => x != null)
.Select(x => x.ToString())
.ToArray();
Here is an extension method that allows the choice of including/excluding nulls, and what value to use to replace null if included.
public static class ObjectArrayExtensions
{
public static string[] ToStringArray(this object[] array, bool includeNulls = false, string nullValue = "")
{
IEnumerable<object> enumerable = array;
if (!includeNulls)
enumerable = enumerable.Where(e => e != null);
return enumerable.Select(e => (e ?? nullValue).ToString()).ToArray();
}
}
Usage:
object[] array = new object[] { 10, "hello", 5, "world", null };
var stringArray = array.ToStringArray();
// stringArray = { "10", "hello", "5", "world" }
stringArray = array.ToStringArray(true);
// stringArray = { "10", "hello", "5", "world", "" }
stringArray = array.ToStringArray(true, "empty");
// stringArray = { "10", "hello", "5", "world", "empty" }
Thanks to 280Z28 for improving the answer.
Try this:
object[] input = {1, 2, null, 4, 5, 0.438, 7};
int[] result = input.OfType<int>().Select((o) => (int)o).ToArray();
// {1, 2, 4, 5, 7}
Or alternative going through string
first:
object[] input = {1, 2, null, 4, 5, 6.438, 7};
int[] result = input.Where((o) => o != null)
.Select((o) =>
{
string s = o.ToString();
int x = 0;
int.TryParse(s, out x);
return x;
}).ToArray();
// { 1, 2, 4, 5, 0, 7}
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