【问题标题】:How to convert a 2D object array to a 2D string array in C#?如何在 C# 中将 2D 对象数组转换为 2D 字符串数组?
【发布时间】:2016-09-25 06:56:06
【问题描述】:

我有一个名为“值”的二维对象数组。我想将其转换为二维字符串数组。我该怎么做?

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

如果可能我也想知道我是否可以将对象转换为

List<List<string>>

直接。

【问题讨论】:

  • 能否请您添加一些代码来理解问题
  • 请确保您已阅读“如何提出一个好问题”。遵循这些准则将使其他人更容易回答,并且您得到的响应会更好并且显示得更快。详细描述在这里:stackoverflow.com/help/how-to-ask
  • 我认为问题标题本身是不言自明的。我只需要一个函数将 2D 对象转换为 2D 字符串数组
  • 什么是“二维对象”?
  • 'object' 是 C# 中许多其他类的基本类。见这里msdn.microsoft.com/en-us/library/system.object(v=vs.110).aspx

标签: c# string object multidimensional-array


【解决方案1】:

这是你要找的吗?

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

【讨论】:

    【解决方案2】:

    要回答您的第一个问题,您可以使用以下方法实现到二维字符串数组的转换:

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

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 2017-04-04
      • 2012-06-01
      • 2016-03-24
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2022-11-18
      相关资源
      最近更新 更多