早上好
我需要一个foreach循环才能逐行打印以下序列:
loop1 a0,a1,a2
loop2 b0,b1,b2
loop3 c0,c1,c2
这是我的第一篇文章,对于任何缺少信息的内容,我们深表歉意。
private void button1_Click(object sender, EventArgs e)
{
int col0_int = 0;
var col0_elements = new string[] { "a0", "b0", "c0", "d0", "e0", "f0", "g0", "h0", };
IList<string> col0_all = col0_elements;
String[] col0_list = new String[col0_all.Count];
List<string> col0_each = new List<string>();
foreach (string element in col0_elements)
{
col0_list[col0_int++] = element;
col0_each.Add(element);
}
int col1_int = 0;
var col1_elements = new string[] { "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", };
IList<string> col1_all = col1_elements;
String[] col1_list = new String[col1_all.Count];
List<string> col1_each = new List<string>();
foreach (string element in col1_elements)
{
col1_list[col1_int++] = element;
col1_each.Add(element);
}
int col2_int = 0;
var col2_elements = new string[] { "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", };
IList<string> col2_all = col2_elements;
String[] col2_list = new String[col2_all.Count];
List<string> col2_each = new List<string>();
foreach (string element in col2_elements)
{
col2_list[col2_int++] = element;
col2_each.Add(element);
}
//LOOP script here
}
答案 0 :(得分:1)
假设所有数组的长度相等:
rowSums
答案 1 :(得分:1)
如果您可以确保三个列表始终在正确的位置包含所需的元素,则快速的解决方案是两次使用LINQ Enumerable.Zip扩展方法:
var results = col0_elements.Zip(col1_elements, (x, y) => $"{x}, {y}")
.Zip(col2_elements, (x, y) => $"{x}, {y}");
这会产生一个IEnumerable<string>
(可以循环播放),其中包含以下内容:
{
"a0, a1, a2",
"b0, b1, b2",
"c0, c1, c2",
"d0, d1, d2",
"e0, e1, e2",
"f0, f1, f2",
"g0, g1, g2",
"h0, h1, h2"
}
答案 2 :(得分:1)
您使事情变得过于复杂。 对于每个字符串数组,您正在创建一个空字符串数组和一个仅包含一个元素的列表... 使用这种方法,您基本上可以创建一个字符串矩阵。
var col0_elements = new string[] { "a0", "b0", "c0", "d0", "e0", "f0", "g0", "h0", };
var col1_elements = new string[] { "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1", };
var col2_elements = new string[] { "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", };
IList<string[]> all_elements = new List<string[]>{ col0_elements, col1_elements, col2_elements };
for (int i = 0; i < col0_elements.Length; i++) // Row iteration
{
foreach (var cell in all_elements) // Cell iteration
{
Console.Write(cell[i]);
}
Console.WriteLine();
}
答案 3 :(得分:0)
您可以使用for循环获取它们:
for (int index = 0; index < col0_each.Count; index++)
{
string col0String = col0_each[index];
string col1String = col1_each[index];
string col2String = col2_each[index];
(print as desired);
}
此代码不包含任何错误检查,以确保每个列表足够长;假设它们的长度都相同。
代码中还有一些可以简化的额外列表,尽管这不是您要的。