[英]In C # how to pass string.empty in a list of string
我有一个字符串列表
Emails = new List<string>() { "R.Dun@domain.co.nz", "S.Dun@domain.co.nz" }
现在我想将string.empty
传递给list的第一个值
就像是
policy.Emails = new List<string>(){string.Empty};
如何为例如list的每个值设置循环以执行某些操作。
您可以将第一个元素直接设置为string.Empty:
policy.Emails[0]=string.Empty;
您可以使用indexof函数在列表中查找字符串,如下所示,
List<string> strList = new List<string>() { "R.Dun@domain.co.nz", "S.Dun@domain.co.nz" };
int fIndex = strList.IndexOf("R.Dun@domain.co.nz");
if(fIndex != -1)
strList[fIndex] = string.Empty;
或者,如果您想将第一个项目替换为string.Empty,那么正如dasblinkenlight所述,您可以直接使用索引,
strList[0] = string.Empty
希望能帮助到你。
您可以在string之前添加string.Empty
到concat的现有列表中:
var emails = new List<string> {"R.Dun@domain.co.nz", "S.Dun@domain.co.nz"};
policy.Emails = new[] {string.Empty}.Concat(emails).ToList();
现在policy.Emails
看起来像这样:
{"", "R.Dun@domain.co.nz", "S.Dun@domain.co.nz"}
如果要替换第一项,请在连接前使用Skip(1)
:
policy.Emails = new[] {string.Empty}.Concat(emails.Skip(1)).ToList();
概括地说,用空字符串替换初始n
值将如下所示:
policy.Emails = Enumerable.Repeat(string.Empty, 1).Concat(emails.Skip(n)).ToList();
注意:不用说,如果您不介意修改列表,最简单的解决方案是
emails[0] = string.Empty;
如果要在列表的开头添加空字符串,可以执行以下操作:
emails.Insert(0, string.Empty);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.