如何在字符串列表的字符串数组中添加字符串数组?

时间:2019-02-10 10:21:45

标签: c# arrays string

我有一个string[,],其数量为string[],该数量保持不变,并希望选择其中一些并将其放入list<string[]>(我使用列表来制作它可以扩展)。但是list<string[]>不会接受来自string[]的任何string[,]

string[,] testArray =
{
    {"testValue1", "testValue1.1"}
    {"testValue2", "testValue2.1"}
    {"testValue3", "testValue3.1"}
}

List<string[]> testList = new List<string[]>();

testList.Add(testArray[1]) //error: wrong number of indicaters inside[]
testList.Add(testArray[1,1]) //error: cannot convert from string to string[]

3 个答案:

答案 0 :(得分:1)

您拥有的是2D数组,而不是jagged array(数组数组)。

您不能直接引用2D数组的整个行(与锯齿状数组不同)。 一种简单的解决方案是使用锯齿状的数组string[][],但如果您不想这样做,可以通过自己遍历2D数组的行并将其缓冲到另一个数组中来实现相同的目的

string[,] testArray =
{
    {"testValue1", "testValue1.1"},
    {"testValue2", "testValue2.1"},
    {"testValue3", "testValue3.1"}
};

List<string[]> testList = new List<string[]>();
string[] arrayRow = new string[testArray.GetLength(1)]; // zero index dimension to get length of

int i = 0; // row to copy
for (int j = 0; j < testArray.GetLength(1); j++) { // loop over row
    arrayRow[j] = testArray[i, j];
}
testList.Add(arrayRow); // {"testValue1", "testValue1.1"} added to list

答案 1 :(得分:0)

  

我有一个字符串[,],其中包含一定数量的字符串[]

实际上这是不正确的,因为您使用的是多维数组而不是锯齿状的数组。如果您使用的是[,],则不能像使用[][]那样直接使用整行。

锯齿状

string[][] testArray =
{
    new [] {"testValue1", "testValue1.1"},
    new [] {"testValue2", "testValue2.1"},
    new [] {"testValue3", "testValue3.1"}
};

Console.WriteLine(string.Join(", ", testArray[0])); //testValue1, testValue1.1

2D阵列

string[,] testArray =
{
    {"testValue1", "testValue1.1"},
    {"testValue2", "testValue2.1"},
    {"testValue3", "testValue3.1"}
};

Console.WriteLine(string.Join(", ", testArray.GetColumn(0))); //testValue1, testValue1.1

public static class ArrayExt
{
    public static IEnumerable<string> GetColumn(this string[,] array, int column)
    {
        return Enumerable.Repeat(column, array.GetLength(1))
            .Zip(Enumerable.Range(0, array.GetLength(1)), (x,y) => new { X = x, Y = y })
            .Select(i => array[i.X, i.Y]);
    }
}

答案 2 :(得分:0)

您可以使用锯齿状数组或2d数组的for循环:

锯齿状阵列:

new string[] {"testValue1", "testValue1.1"},
new string[] {"testValue2", "testValue2.1"},
new string[] {"testValue3", "testValue3.1"}
};

List<string[]> testList = new List<string[]>();

testList.Add(testArray[1]); //second row of jagged array

2d数组:

string[,] testArray =
{
 {"testValue1", "testValue1.1"},
 {"testValue2", "testValue2.1"},
 {"testValue3", "testValue3.1"}
};

List<string[]> testList = new List<string[]>();
string[] secnd_rw=new string[testArray.GetLength(1)] ;
for (int i = 0; i < testArray.GetLength(1); i++)
{
    secnd_rw[i] = testArray[1,i];
}
testList.Add(secnd_rw); //second row of 2d array
相关问题