C# 循环遍历集合并将每个对象分配给变量
我确信这很简单,但我似乎无法做到这一点。 我建立了一个用户 ICollection。该集合可以有 1 个或多个。 我现在想要循环遍历这个集合,并为每个用户分配一个变量,然后我可以用它来填写电子表格。
目前我有这段代码:
string username = null;
foreach (var user in dailyReport)
{
username = user.UserName;
}
Cell cell= worksheet.Cells["B5"];
cell.PutValue(username);
现在显然这只是将集合的最后一个用户放入单元格 B5 中! 如何收集所有 user.UserNames,以便将它们放置在 B5、B6、B7 等中???
I am sure this is quite simple but I cannot seem to get this right.
I have a built up a ICollection of Users. This collection could have 1 or many.
I now want to loop through this collection and assign a variable to each user that I can then use to fill in a spread sheet.
At present I have this code :
string username = null;
foreach (var user in dailyReport)
{
username = user.UserName;
}
Cell cell= worksheet.Cells["B5"];
cell.PutValue(username);
Now obviously this just puts the last user of the collection into cell B5!
How do I collect all user.UserNames so I can place them in B5, B6, B7 and so on????
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要获取用户名列表:
或者,您可以直接在循环中进行分配:
To get a list of the user names:
Alternatively you can just do the assignment in the loop directly:
您需要将值放入
foreach
循环内部。您要求的具体事情(为集合中的每个值获取不同的变量)是不可能的,而且也不是您想要的。You need to put the value inside the
foreach
loop. The specific thing you are asking for--getting a different variable for every value in the collection--is not possible, and isn't what you want anyway.