How to convert object to object[]

前端 未结 4 1704
孤城傲影
孤城傲影 2021-01-17 10:52

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[]

相关标签:
4条回答
  • 2021-01-17 11:39
    void Do(object value)
    {
        if (value.GetType().IsArray)
        {
           string[] strings = ((object[]) value).Select(obj => Convert.ToString(obj)).ToArray();
        }
    }
    
    0 讨论(0)
  • 2021-01-17 11:40

    .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();
    
    0 讨论(0)
  • 2021-01-17 11:43

    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.)

    0 讨论(0)
  • 2021-01-17 11:44

    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.

    0 讨论(0)
提交回复
热议问题