我有一个正在编写的应用程序,我必须在其中将街道地址放在预定义的标签纸上。此标签页有 3 列和 10 行。我有正确创建标签的循环,但需要允许用户能够选择工作表上的哪个标签开始。我原以为这将是一个简单的数学矩阵方程,但我无法想出或找到解决方案。
这是一个例子:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
鉴于上面的矩阵,假设用户决定从#6 开始。我需要能够告诉我的循环从该位置开始:col:1 row:2。
如果有帮助,我的循环看起来像这样,但我认为这归结为我没有想到的数学方程式:
for (var yCounter = 0; yCounter < _labelSettings.LabelPerColumn; yCounter++)
{
for (var xCounter = 0; xCounter < _labelSettings.ColumnsPerPage; xCounter++)
{
foreach (var table in customNugget.PdfTables)
{
table.YPosition = SheetSettings.PageHeight -
(verticalOffset + yCounter * ((verticalSize + verticalOffset)));
table.XPosition = horizontalOffset + xCounter * ((horizontalSize + horizontalOffset));
}
}
}
编辑
private static int _cellsPerRow = 3;
private static int _startIndex;
static void Main(string[] args)
{
string userInput = Console.ReadLine();
_startIndex = int.Parse(userInput);
int startY = _startIndex / _cellsPerRow;
int startX = (_startIndex - 1) % _cellsPerRow;
Console.WriteLine(string.Format("The index you chose lives in the following matrix location:\n Row: {0} Column: {1}", startY, startX));
Console.WriteLine("Press any key to continue...");
Console.Read();
}
最佳答案
假设您知道每行中的单元格数(我认为应该是 _labelSettings.ColumnsPerPage
),您可以像这样计算起始值:
int cells = 5;//number of cells per row
int startAt = 6;//cell number to start at
int startY = (startAt - 1) / cells;//1
int startX = (startAt - 1) % cells;//0
然后您可以使用这些起始值来初始化您的循环,但是您需要小心确保您的内部循环仅在第一次运行时使用计算出的起始值。为此,您可以在第一次执行 y 循环后重置 startX
。像这样:
for (var yCounter = startY; yCounter < _labelSettings.LabelPerColumn; yCounter++)
{
for (var xCounter = startX; xCounter < _labelSettings.ColumnsPerPage; xCounter++)
{
//do stuff
}
startX = 0;//reset so that the next execution starts at the beginning of the row
}
Here is proof of the logic, though it is in javascript
编辑:startY
的计算已被修改以正确处理从最后一个数字开始的一行(感谢@Zach 指出错误)
关于c# - 给定一个网格中的位置,它是什么行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19730675/