将对象[,]转换为字符串[,]?

时间:2013-04-30 10:36:29

标签: c#

您如何将object[,]转换为string[,]

Object[,] myObjects= // sth
string[,] myString = // ?!? Array.ConvertAll(myObjects, s => (string)s) // this doesn't work

任何建议表示赞赏。

编辑:当然,循环解决方案显然会做到这一点,但我在组织和性能方面都设想了更优雅的解决方案。

EDIT2:object[,]当然包含string个(和数字,但现在这无关紧要。)

4 个答案:

答案 0 :(得分:4)

Object[,] myObjects = new Object[3, 2] { { 1, 2 }, { 3, 4 },
                                        { 5, 6 } };

string[,] myString = new string[3, 2];

for (int i = myObjects.GetLowerBound(0); i < myObjects.GetUpperBound(0); i++)
{
     for (int j = myObjects.GetLowerBound(1); j < myObjects.GetUpperBound(1); j++)
     {
          myString[i, j] = myObjects[i, j].ToString();
     }
}

foreach (var item in myString)
{
    Console.WriteLine("{0} - {1}", item.GetType(), item);
}

输出将是;

System.String - 1
System.String - 2
System.String - 3
System.String - 4
System.String - 5
System.String - 6

答案 1 :(得分:4)

您可以像这样分配空间

string[,] myString = new string[myObjects.GetLength(0),myObjects.GetLength(1)];

然后一些循环应该可以正常工作,如下所示:

for(int k=0;k < myObjects.GetLength(0);k++)
    for(int l=0;l < myObjects.GetLength(1);l++)
        myString[k,l] = myObjects[k,l].ToString();

答案 2 :(得分:4)

鉴于其他答案,为2D阵列编写自己的ConvertAll方法非常容易:

public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Func<TInput, TOutput> converter)
{
    var result = new TOutput[array.GetLength(0), array.GetLength(1)];
    for (int i = 0; i < array.GetLength(0); ++i)
        for (int j = 0; j < array.GetLength(1); ++j)
            result[i, j] = converter(array[i, j]);

    return result;
}

仅仅因为.NET的作者并不关心这种方法,所以没有必要完全放弃。你自己写它是非常直接的。

(如果你愿意的话,你可以把它变成一种扩展方法。)

评论后编辑:如果你真的想处理下限(在某个维度上)不为零的数组,它会是这样的:

public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Func<TInput, TOutput> converter)
{
    int xMin = array.GetLowerBound(0);
    int xLen = array.GetLength(0);
    int yMin = array.GetLowerBound(1);
    int yLen = array.GetLength(1);
    var result = (TOutput[,])Array.CreateInstance(typeof(TOutput), new[] { xLen, yLen, }, new[] { xMin, yMin, });
    for (int x = xMin; x < xMin + xLen; ++x)
        for (int y = yMin; y < yMin + yLen; ++y)
            result[x, y] = converter(array[x, y]);

    return result;
}

答案 3 :(得分:3)

这应该是最简单和最快速的方法之一,假设src数组中的每个元素都可以转换为dst数组类型。

object[,] src = new object[,]
{
    {"foo", "bar"},
    {"spam", "eggs"},
};

string[,] dest = new string[src.GetLength(0), src.GetLength(1)];
Array.Copy(src, dest, src.Length);
相关问题