将一维数组的索引转换为二维数组,即行和列。

8
我有一个使用WinForms的应用程序,其中我在列表框中插入名称和价格。名称和价格分别存储在二维数组中。现在,当我从列表框中选择一条记录时,它只给我一个索引,我可以从中获取字符串名称和价格以更新该记录,我必须更改该索引处的名称和价格,因此我想更新两个二维数组的名称和价格。但是所选索引只是一维的。我想将该索引转换为行和列。如何做到这一点?
但我是这样向列表框中插入记录的。
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);
    }
}

1
你应该发布一些代码... - DotNetRussell
3个回答

43

虽然我没有完全理解具体的情况,但将 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

如何处理多维数组? - Vlad

0

试试这个,

int i = OneDimensionIndex%NbColumn
int j = OneDimensionIndex/NbRow //Care here you have to take the integer part

如果源数组包含类似于“名称 价格 名称 价格...”的序列,则此代码是正确的。然而,这并不是真正的二维数组。 - Thorsten Dittmar

0

嗯,如果我理解你的意思正确的话,在你的情况下,显然 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;

你觉得在问题中加入相关的源代码部分怎么样?这不是应该在评论中发布的东西。 - Thorsten Dittmar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接