简体   繁体   中英

How to convert a 2D object array to a 2D string array in C#?

I have a 2D array of objects called 'value'. I want to convert it to a 2D string array. How do I do this?

object value; //This is a 2D array of objects
string prop[,]; //This is a 2D string

If possible I would also like to know if I can convert the object to

List<List<string>>

directly.

Is this what you are looking for?

        string[,] prop; //This is a 2D string
        List<List<string>> mysteryList;

        if (value is object[,])
        {
            object[,] objArray = (object[,])value;

            // Get upper bounds for the array
            int bound0 = objArray.GetUpperBound(0);//index of last element for the given dimension
            int bound1 = objArray.GetUpperBound(1);

            prop = new string[bound0 + 1, bound1 + 1];
            mysteryList = new List<List<string>>();

            for (int i = 0; i <= bound0; i++)
            {
                var temp = new List<string>();

                for (int j = 0; j <= bound1; j++)
                {
                    prop[i, j] = objArray[i, j].ToString();//Do null check and assign 
                    temp.Add(prop[i, j]);
                }
                mysteryList.Add(temp);
            }
        }

To answer your first question you can achieve the conversion to a 2D string array with this:

    List<string[]> objectValues = new List<string[]>
    {
       new[] { "1", "2", "3" },
       new[] { "A", "B", "C" },
    };

    string[,] prop = ConvertObjectListArray(objectValues );

    public T[,] ConvertObjectListArray<T>(IList<T[]> objectList)
    {
        int Length2 = objectList[0].Length;
        T[,] ret = new T[objectList.Count, Length2];
        for (int i = 0; i < objectList.Count; i++)
        {
            var array = objectList[i];
            if (array.Length != Length2)
            {
                throw new ArgumentException
                    ("All arrays must be the same length");
            }
            for (int i2 = 0; i2 < Length2; i2++)
            {
                ret[i, i2] = array[i2];
            }
        }
        return ret;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM