Converting a Object[] Array to an String[] Array in C#? [Closed]

Converting a Object[] Array to an String[] Array in C#? [Closed]

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

0

4 Answers

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());
2

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();
0

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.

2

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}
Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.