C#遍历一个集合并将每个对象分配给一个变量
问题描述:
我相信这很简单,但我似乎无法得到正确的结果。 我建立了一个ICollection用户。这个集合可以有1个或多个。 我现在想循环访问这个集合并为每个用户分配一个变量,然后我可以使用它来填充电子表格。C#遍历一个集合并将每个对象分配给一个变量
目前我有这样的代码:
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等等中?
答
你需要把价值内的foreach
循环。您所要求的具体事情 - 为集合中的每个值获取不同的变量 - 是不可能的,而且不是您想要的。
string column = "B"; // or whatever your column is
int row = 1; // or whatever your starting value is
foreach (var user in dailyReport)
{
string username = user.UserName;
string cellAddress = String.Format("{0}{1}", column, row);
Cell cell = worksheet.Cells[cellAddress];
cell.PutValue(username);
row++; // make sure to increment the row, or every username goes in the same cell
}
答
获取用户名列表:
List<string> userNames = dailyReport.Select(x=> x.UserName).ToList();
或者你可以做直接循环分配:
int index = 5;
foreach (var user in dailyReport)
{
Cell cell= worksheet.Cells["B"+ index.ToString()];
cell.PutValue(user.UserName);
index++;
}
答
int i = 5;
foreach (var user in dailyReport)
{
worksheet.Cells["B" + (i++).ToString()].PutValue(user.UserName);
}
感谢您的快速回复。这个工作就像我想要的一样,你解释得很清楚。也感谢@Tony Lukasavage,他的回答也很有效。非常干净的代码! – freerider11 2011-04-26 16:29:14