[英]Converting four arrays into single 2D array in C#
根據先前的分配,我們有4個數組:
string[] titles = new string[10];
string[] authors = new string[10];
string[] publishers = new string[10];
string[] dates = new string[10];
在此分配中,我們必須將所有這些轉換為單個2D數組。 我知道如何聲明一個2D數組(例如int[,] items = new int[4, 6];
),但是要將4個數組放入單個2D數組中,這讓我很頭疼。 任何幫助,不勝感激。
如果您需要專門用於學術目的的2D陣列 。 請注意,您應該改用鋸齒狀的數組(請參閱最后的注釋!)
string[] titles = new string[10];
string[] authors = new string[10];
string[] publishers = new string[10];
string[] dates = new string[10];
string[,] array2D = new string[4, 10];
for (int i = 0; i < 4; i++)
{
string[] myCurrentArray = new string[] { };
switch (i)
{
case 0:
myCurrentArray = titles;
break;
case 1:
myCurrentArray = authors;
break;
case 2:
myCurrentArray = publishers;
break;
case 3:
myCurrentArray = dates;
break;
default:
break;
}
for (int j = 0; j < 10; j++)
{
array2D[i, j] = myCurrentArray[j];
Console.WriteLine("Array [" + i + "][" + j + "]: " + array2D[i, j]);
}
}
簡要說明,您需要做的是手動填充多維魔術裝置。 為了檢索這些值,您需要進行很多調用,這確實很慢。 鑒於已經在數組中填充了數據 ,最有效的方法是動態選擇這4個數組,然后循環遍歷以檢索數據並將其插入2D數組。
第一個循環遍歷所有4個數組,並為每個數組提供實例,以避免以后再重復執行代碼,此開關將對此進行處理。 第二個循環遍歷每個數組,並檢索數據以正確存儲它。
我假設您已經知道循環的工作原理,不過我要明確指出請謹慎使用ARRAY BOUNDS 。 如果嘗試將此代碼重用於具有不同大小的數組,則可能會遇到Array out of bounds Exception
Array.Length
Array out of bounds Exception
,因此請相應地修改代碼,並根據需要使用Array.Length
循環上限,等等。
這是您應該做的(使用鋸齒狀數組):
string[] titles = new string[10];
string[] authors = new string[10];
string[] publishers = new string[10];
string[] dates = new string[10];
string[][] table = new string[][] { titles, authors, publishers, dates };
table
將在單個變量中包含所有4個數組。
請閱讀此內容沒有理由在交錯的數組上使用多維數組,它們速度較慢,它們不接受您已經擁有的對象類型(字符串數組),並且將迫使您遍歷並用幾個填充數據嵌套循環。
請檢查有關交錯數組和多維數組的信息,並了解它們之間的區別: 多維數組和C#中的數組數組之間有什么區別?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.