我有一个列表,我想用它来创建一个均匀分布在列中的表 所以我会接受:
function_id
exception rpt
alarm maint
ratio adder
temp ratio
change
access
aet sequence
eng display
line set
clear repeaters
enable function
volt setpoint
feed setpoint
feed report
volt report
problem pot
temp voltage
flag pc in/out
tap enable
并创建以下内容(对格式抱歉):
Col1--------------Col2--------------Col3--------------Col4--------------Col5--------------Col6
exception rpt eng display volt report ae map search/starve amps volts
alarm maint line set problem pot exception log votrax watch search screen
ratio adder clear repeaters temp voltage pot status bath, metal newpot
temp ratio enable function flag pc in/out noise report alarm watch pcram v/o
change volt setpoint tap enable select pots repeater check
access feed setpoint set enable shift summary pcram
aet sequence feed report enable status trace report ratio entry
我现在的工作原理似乎应该有一种更有效的方式:
public DataTable CreateMenuTable()
{
DataTable userFunctions = GetMenus();
DataTable menuTable = new DataTable();
DataRow menuRow;
int rowNum = 0;
int numColumns = (int)Math.Sqrt(userFunctions.Rows.Count);
int numRows = (int)Math.Ceiling(userFunctions.Rows.Count / (float)numColumns);
for (int i = 0; i < numColumns; i++)
{
menuTable.Columns.Add(new DataColumn("Col" + (i + 1), System.Type.GetType("System.String")));
}
for (int i = 0; i < numRows; i++)
{
menuRow = menuTable.NewRow();
menuTable.Rows.Add(menuRow);
}
foreach (DataRow row in userFunctions.AsEnumerable())
{
if (rowNum < numRows)
{
menuRow = menuTable.Rows[rowNum];
menuRow["Col1"] = row["function_id"];
}
if (rowNum >= numRows & rowNum < (numRows * 2))
{
menuRow = menuTable.Rows[rowNum - (numRows)];
menuRow["Col2"] = row["function_id"];
}
if (rowNum >= (numRows * 2) & rowNum < (numRows * 3))
{
menuRow = menuTable.Rows[rowNum - (numRows * 2)];
menuRow["Col3"] = row["function_id"];
}
if (rowNum >= (numRows * 3) & rowNum < (numRows * 4))
{
menuRow = menuTable.Rows[rowNum - (numRows * 3)];
menuRow["Col4"] = row["function_id"];
}
if (rowNum >= (numRows * 4) & rowNum < (numRows * 5))
{
menuRow = menuTable.Rows[rowNum - (numRows * 4)];
menuRow["Col5"] = row["function_id"];
}
if (rowNum >= (numRows * 5) & rowNum < (numRows * 6))
{
menuRow = menuTable.Rows[rowNum - (numRows * 5)];
menuRow["Col6"] = row["function_id"];
}
rowNum++;
}
return menuTable;
}
答案 0 :(得分:0)
您可以避免所有if
这样的事情:
// Calculate to which column this should belong
int columnNumber = rowNum / numRows + 1;
// % just return the remainder of the division between two numbers
// if you think about it it's the same as rowNum - (numRows)*K
menuRow = menuTable.Rows[rowNum % numRows];
// put it in the right column
menuRow["Col"+columnNumber] = row["function_id"];