为了安全处理,我创建了一个电子邮件列表,该列表由分号分隔。
但是查看日志时,用户在每封电子邮件之后输入一个逗号",“字符,这会导致An invalid character was found in the mail header: ','
错误。
我确实看过关于从列表中删除字符的其他答案,并使用Linq尝试了以下内容:
//Remove any invalid commas from the recipients list
recipients = string.Join(" ", recipients .Split().Where(w => !recipients.Contains(",")));
但是编译器告诉我,List<string>
不包含当前上下文中不存在的.Split()
定义。在去掉逗号后,处理后的列表保持";“分号分隔是很重要的。
问题:
如何从分号分隔列表中删除逗号字符?
代码:
List<string> recipients = new List<string>();
//Split the additional email string to List<string>
// (check that the string isn't empty before splitting)
if(string.IsNullOrEmpty(adContacts.AdditionalEmails) != true)
{ recipients = adContacts.AdditionalEmails.Split(';').ToList(); }
//Remove any invalid commas from the recipients list
recipients = string.Join(" ", text.Split().Where(w => !recipients.Contains(",")));
发布于 2016-07-18 03:01:33
这取决于你说删除所有逗号是什么意思。删除整个text
中的逗号
text = text.Replace(",", "");
在你的情况下
recipients = adContacts.AdditionalEmails
.Replace(",", "")
.Split(';')
.ToList(); // <- do you really want to convert array into a list?
将命令转换为分号
text = text.Replace(',', ';');
若要删除包含逗号的所有eMails:
recipients = string.Join(";", text
.Split(';')
.Where(w => !w.Contains(",")));
最后,您可以将逗号作为一个有效的分隔符以及分号:
var eMails = text.Split(new char[] {';', ','}, StringSplitOptions.RemoveEmptyEntries);
发布于 2016-07-18 02:58:57
编译器错误是因为收件人是列表而不是字符串,而List的收件人没有拆分方法。
因此,使用List.RemoveAll方法:
// Remove any invalid commas from the recipients list.
recipients = string.Join(" ", recipients.RemoveAll(item => item.Contains(",")));
发布于 2016-07-18 03:02:48
您可能希望用分号替换所有逗号:
recipients=recipients.Replace(",",";");
https://stackoverflow.com/questions/38434931
复制