我认为这是直截了当的,但给出了一个多维数组
string[,] table = new string[,]
{
{"Apple", "Banana", "Clementine", "Damson"},
{"Elderberry", "Fig", "Grape", "Huckleberry"},
{"Indian Prune", "Jujube", "Kiwi", "Lime"}
};
如何使用索引返回特定数组?
我尝试了以下但不起作用。
string[] firstArray = table[0];
谢谢。
答案 0 :(得分:1)
您可以像这样使用锯齿状数组:
string[][] table = new string[3][]
{
new string[] {"Apple", "Banana", "Clementine", "Damson"},
new string[] {"Elderberry", "Fig", "Grape", "Huckleberry"},
new string[] {"Indian Prune", "Jujube", "Kiwi", "Lime"}
};
string[] array = table[0];
OR
如果您对使用锯齿状数组不感兴趣,可以使用扩展方法,如:
public static class MyExtensions
{
public static string[] GetArray(this string[,] table, int dimension )
{
string[] array = new string[table.GetLength(dimension)];
for (int i = 0; i < array.Length; i++)
{
array[i] = table[dimension, i];
}
return array;
}
}
然后通过传递您想要的尺寸获得任何尺寸:
string[] firstArray = table.GetArray(0);
希望这会有所帮助
答案 1 :(得分:1)
C#中的多维数组和锯齿状数组之间存在差异。如果您的数组定义如下:
string[][] table = new string[][]
{
new string[] {"Apple", "Banana", "Clementine", "Damson"},
new string[] {"Elderberry", "Fig", "Grape", "Huckleberry"},
new string[] {"Indian Prune", "Jujube", "Kiwi", "Lime"}
};
然后你的线就行了。要从多维数组中获取一行,您可以执行以下操作:
string[] firstRow = new string[table.GetLength(1)];
for (int i = 0; i < firstRow.Length; i++)
{
firstRow[i] = table[0, i];
}
答案 2 :(得分:1)
Forr你最好的方法是在数组上的扩展方法。然后你可以在任何地方调用它。 请看下面的内容。一旦实现扩展方法,您的项目中可能有许多此类数组,您可以将任何数组应用于table.method(row)
public static class ext{
public static string[] twodim(this string[,] inarr, int row) {
string[] ret = new string[inarr.GetLength(1)];
for (int i = 0; i < inarr.GetLength(1); i++)
ret[i] = inarr[row, i];
return ret;
}
}
public class Program{
static void dump(string name, string[] arr){
Console.WriteLine(name);
for (int i = 0; i < arr.Length; i++)
Console.WriteLine(" {0} ", arr[i]);
}
static void Main(string[] args){
string[,] table = new string[,] {
{"Apple", "Banana", "Clementine", "Damson"},
{"Elderberry", "Fig", "Grape", "Huckleberry"},
{"Indian Prune", "Jujube", "Kiwi", "Lime"}
};
dump("Row 0", table.twodim(0));
dump("Row 0", table.twodim(1));
dump("Row 0", table.twodim(2));
}
答案 3 :(得分:0)
如果您需要特定语法,则需要使用锯齿状数组AFAIK。
string[][] table = new string[][]
{
new string[]{"Apple", "Banana", "Clementine", "Damson"},
new string[]{"Elderberry", "Fig", "Grape", "Huckleberry"},
new string[]{"Indian Prune", "Jujube", "Kiwi", "Lime"}
};
string[] firstArray = table[0];
您指定的二维数组需要表[0,N]从表中检索单个元素。
答案 4 :(得分:0)
简单的方法,
string[,] table = new string[,]
{
{"Apple", "Banana", "Clementine", "Damson"},
{"Elderberry", "Fig", "Grape", "Huckleberry"},
{"Indian Prune", "Jujube", "Kiwi", "Lime"}
};
string[] arr = new string[table.GetLength(1)];
for (int index = 0; index < table.Length; index++)
{
arr[index] = table[0,index];
}
锯齿状阵列也是一种选择。