C# 如何索引数组
C# How to index arrays
当我在另一个组合框中 select 项目并单击按钮时,我想在组合框中添加特定数组的字符串。有两个数组,S0 和 S1。在 S0 中有数学教学大纲的字符串,在 S1 中有英语教学大纲的字符串。
我的代码:
for (int x = 0; x <= 1 ; x++)
{
if (comboBox1.SelectedIndex == x)
{
foreach (string items in S+x )
{
comboBox2.Items.Add(items);
}
}
}
如果我理解正确,那么你想在情况 1 中使用数组 S0,其中 x==0 和 S1,其中 x==1。如果 S0 和 S1 是同一类型,例如string[] 你可以试试
for (int x = 0; x <= 1 ; x++)
{
if (comboBox1.SelectedIndex == x)
{
var stringArray = x==0 ? S0 : S1; // select array S0 or S1 dependent on value of X
foreach (string items in stringArray)
{
comboBox2.Items.Add(items);
}
}
}
并且您可以考虑在添加新元素之前清除 combobox2 项目,方法是添加行
comboBox2.Items.Clear()
在 foreach
循环之前
除非您打算向系统添加额外的主题,否则只需使用 2 个单独的 foreach 循环。如果要使其可扩展,请使用二维字符串数组:
string[,] data;
//Fill data here using the first dimension for the subjects and the second for the different items in the subject. data[0,0] could be "Pythagoras" and data[1,0] "Shakespeare" for example.
for (int i=0; i<data.GetLength(0); i++)
{
for (int j=0; j<data.GetLength(1); j++)
{
comboBox2.Items.Add(data[i, j]);
}
}
当我在另一个组合框中 select 项目并单击按钮时,我想在组合框中添加特定数组的字符串。有两个数组,S0 和 S1。在 S0 中有数学教学大纲的字符串,在 S1 中有英语教学大纲的字符串。
我的代码:
for (int x = 0; x <= 1 ; x++)
{
if (comboBox1.SelectedIndex == x)
{
foreach (string items in S+x )
{
comboBox2.Items.Add(items);
}
}
}
如果我理解正确,那么你想在情况 1 中使用数组 S0,其中 x==0 和 S1,其中 x==1。如果 S0 和 S1 是同一类型,例如string[] 你可以试试
for (int x = 0; x <= 1 ; x++)
{
if (comboBox1.SelectedIndex == x)
{
var stringArray = x==0 ? S0 : S1; // select array S0 or S1 dependent on value of X
foreach (string items in stringArray)
{
comboBox2.Items.Add(items);
}
}
}
并且您可以考虑在添加新元素之前清除 combobox2 项目,方法是添加行
comboBox2.Items.Clear()
在 foreach
循环之前
除非您打算向系统添加额外的主题,否则只需使用 2 个单独的 foreach 循环。如果要使其可扩展,请使用二维字符串数组:
string[,] data;
//Fill data here using the first dimension for the subjects and the second for the different items in the subject. data[0,0] could be "Pythagoras" and data[1,0] "Shakespeare" for example.
for (int i=0; i<data.GetLength(0); i++)
{
for (int j=0; j<data.GetLength(1); j++)
{
comboBox2.Items.Add(data[i, j]);
}
}