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

问题描述 投票:1回答:3

我有一个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[]
c# arrays string
3个回答
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

0
投票

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

锯齿状阵列:

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

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]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.