如何获取列表项的字符串值
本文关键字:字符串 列表 何获取 获取 | 更新日期: 2023-09-27 17:55:12
我有一些文件路径存储在列表中,需要将它们附加到电子邮件中。但是,如何访问列表项的值(在我的例子中:文件路径作为字符串值)?
这是代码:
List<string> filesToSend = new List<string>();
filesToSend = (List<string>)Session["filesListForFilesToSend"];
for (int i = 0; i < filesToSend.Count; i++)
{
//message.Attachments.Add(filesToSend[i].????????????????????);
}
提前致谢
filesToSend[i] 将返回你想要的路径字符串
试试这个
foreach(string EachString in filesToSend)
{
message.Attachments.Add(EachString)
}
首先,在会话中读取列表后,您不需要实例化第一个列表,只需:
List<string> filesToSend = (List<string>)Session["filesListForFilesToSend"];
当您通过index
访问和List
时,您将获得泛型类型的对象。对于示例,您可以使用多种方式来做到这一点:
使用for
循环:
for (int i = 0; i < filesToSend.Count; i++)
message.Attachments.Add(filesToSend[i]);
或foreach
foreach(string file in filesToSend)
message.Attachments.Add(file);
或while
int i = filesToSend.Lenght;
while(i--)
message.Attachments.Add(filesToSend[i]);
我会使用foreach
语句,但while
会给你更多的性能(请记住,你将以相反的顺序循环)。
错误不是我试图从列表中获取字符串的方式。错误是我试图将其附加到我的消息中的方式。
for (int i = 0; i < filesToSend.Count; i++)
{
string filePath = filesToSend[i];
Attachment attached = new Attachment(filePath);
attached.Name = filePath;
message.Attachments.Add(attached);
}
这就是它对我的工作方式。谢谢大家