Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
834 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
            }
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...