将一维数组的索引转换为二维数组,即行和列
我有一个WinForms
应用程序,我在插入名单和价格..名称和价格分别存储在二维数组。 现在,当我从listbox
选择一条记录时,它只给我一个索引,我可以从中获取字符串名称和价格以更新该记录我必须更改该索引的名称和价格为此我要更新二维数组名称和价格。 但所选索引只是一维的。 我想将该索引转换为行和列。 怎么做?
但我正在这样的列表框中插入记录。
int row = 6, column = 10; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { value= row+" \t "+ column +" \t "+ name[i, j]+" \t " +price[i, j]; listbox.items.add(value); } }
虽然我没有完全理解确切的情况,但在1D和2D坐标之间进行平移的常用方法是:
从2D到1D:
index = x + (y * width)
要么
index = y + (x * height)
取决于您是从左到右还是从上到下阅读。
从1D到2D:
x = index % width y = index / width
要么
x = index / height y = index % height
试试这个,
int i = OneDimensionIndex%NbColumn int j = OneDimensionIndex/NbRow //Care here you have to take the integer part
好吧,如果我理解正确,在你的情况下,显然ListBox
条目的数组条目的索引是ListBox
的索引。 然后,名称和价格在该数组元素的索引0
和索引1
处。
例:
string[][] namesAndPrices = ...; // To fill the list with entries like "Name: 123.45" foreach (string[] nameAndPrice in namesAndPrices) listBox1.Items.Add(String.Format("{0}: {1}", nameAndPrice[0], nameAndPrice[1])); // To get the array and the name and price, it's enough to use the index string[] selectedArray = namesAndPrices[listBox1.SelectedIndex]; string theName = selectedArray[0]; string thePrice = selectedArray[1];
如果你有这样的数组:
string[] namesAndPrices = new string[] { "Hello", "123", "World", "234" };
事情是不同的。 在那种情况下,指数是
int indexOfName = listBox1.SelectedIndex * 2; int indexOfPrice = listBox1.SelectedIndex * 2 + 1;