Skip to main content
 首页 » 编程设计

c#之按照 C# 中的模式在集合中生成值

2024年01月24日26powertoolsteam

我有以下标签字符串列表:

List<string> Tags = new List<string> { "EmplId", "EmpName", "EmpAddress" }; 

我想生成如下模式的标签:

EmplId1 
EmpName1 
EmpAddress1 
EmplId2 
EmpName2 
EmpAddress2 
EmplId3 
EmpName3 
EmpAddress3 

我写了下面的代码:

List<string> Tags = new List<string> { "EmplId", "EmpName", "EmpAddress" }; 
foreach (var item in Tags) 
{ 
    for (int i = 1; i < 4; i++) 
    { 
        Console.WriteLine(item+i); 
    } 
} 
Console.ReadLine(); 

但是这段代码生成的输出如下:

EmplId1 
EmplId2 
EmplId3 
EmpName1 
EmpName2 
EmpName3 
EmpAddress1 
EmpAddress2 
EmpAddress3 

如何获得所需的输出?

请您参考如下方法:

内循环确实需要成为外循环。你想迭代数字然后迭代值

for (int i = 1; i < 4; i++) 
{ 
  foreach (var item in Tags) 
  { 
     Console.WriteLine(item+i); 
  } 
}